【问题标题】:Pandas - make a column dtype object or FactorPandas - 制作列 dtype 对象或因子
【发布时间】:2013-03-21 08:35:11
【问题描述】:

在 pandas 中,如何将 DataFrame 的列转换为 dtype 对象? 或者更好的是,成为一个因素? (对于会说 R 的人,在 Python 中,我该如何as.factor()?)

另外,pandas.Factorpandas.Categorical 有什么区别?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以使用astype 方法投射一个系列(一列):

    df['col_name'] = df['col_name'].astype(object)
    

    或者整个DataFrame:

    df = df.astype(object)
    

    更新

    Since version 0.15, you can use the category datatype 在系列/列中:

    df['col_name'] = df['col_name'].astype('category')
    

    注意:pd.Factor 已被弃用并已被删除以支持pd.Categorical

    【讨论】:

    • 非常感谢,这让您头疼不已。
    • 尝试这个时我得到“TypeError:数据类型不理解”我正在尝试这个 data['engagement'] = data['engagement'].astype(data) AND data = data .astype(数据)。我的专栏是engagement 5000 non-null float64
    • 你需要使用对象吗? data['engagement'].astype(object)...如果它们已经是浮动的,为什么要更改为对象?
    • 注意:另外,当这个原始答案被写入创建一个分类然后将它设置为一个列时,该列被转换为对象(或另一个 dtype),因为你不能(直到 0.15)有分类列/系列。
    【解决方案2】:

    还有 pd.factorize 函数可以使用:

    # use the df data from @herrfz
    
    In [150]: pd.factorize(df.b)
    Out[150]: (array([0, 1, 0, 1, 2]), array(['yes', 'no', 'absent'], dtype=object))
    In [152]: df['c'] = pd.factorize(df.b)[0]
    
    In [153]: df
    Out[153]: 
       a       b  c
    0  1     yes  0
    1  2      no  1
    2  3     yes  0
    3  4      no  1
    4  5  absent  2
    

    【讨论】:

      【解决方案3】:

      据我所知,FactorCategorical 是相同的。我认为它最初被称为因子,然后改为分类。要转换为分类,也许您可​​以使用pandas.Categorical.from_array,如下所示:

      In [27]: df = pd.DataFrame({'a' : [1, 2, 3, 4, 5], 'b' : ['yes', 'no', 'yes', 'no', 'absent']})
      
      In [28]: df
      Out[28]: 
         a       b
      0  1     yes
      1  2      no
      2  3     yes
      3  4      no
      4  5  absent
      
      In [29]: df['c'] = pd.Categorical.from_array(df.b).labels
      
      In [30]: df
      Out[30]: 
         a       b  c
      0  1     yes  2
      1  2      no  1
      2  3     yes  2
      3  4      no  1
      4  5  absent  0
      

      【讨论】:

      • 请注意,上述用法已被弃用,需要按如下方式使用:pd.Categorical(df.b).codes
      猜你喜欢
      • 2016-01-15
      • 1970-01-01
      • 1970-01-01
      • 2023-02-10
      • 1970-01-01
      • 1970-01-01
      • 2018-09-30
      • 2014-04-03
      • 2019-06-16
      相关资源
      最近更新 更多