【问题标题】:How do I load categorical variable with pandas read_csv?如何使用 pandas read_csv 加载分类变量?
【发布时间】:2016-05-09 16:39:17
【问题描述】:

将数据加载到数据框中并自动转换为分类变量时出现以下错误。

df = pd.read_csv(filepath_or_buffer=filename,
                 header=0,
                 index_col=False,
                 usecols=['col1', 'col2', 'col3'],
                 dtype={'col1': int,
                        'col2': 'category',
                        'col3': float})

TypeError:数据类型“类别”不理解

【问题讨论】:

    标签: python pandas machine-learning


    【解决方案1】:

    目前尚未实现,但您可以使用以下解决方法:

    dtype={'col1': int,
           'col2': pd.CategoricalDtype(['cat1', 'cat2', 'cat3']),
           'col3': float}
    

    here 仍然是开放功能请求

    【讨论】:

      【解决方案2】:

      最简单的做法是事后将其转换为分类,尤其是考虑到在阅读文件之前您可能不知道所有有效类别。

      df = pd.read_csv(filepath_or_buffer=filename, usecols=['col1', 'col2', 'col3'])
      df['col3'] = df.col3.astype('category')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-19
        • 1970-01-01
        • 2018-02-04
        • 2016-11-13
        • 2013-04-08
        • 2015-07-28
        相关资源
        最近更新 更多