Pandas - 制作列dtype对象或因子

N. *_*cA. 46 python pandas

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

另外,pandas.Factor和之间的区别是pandas.Categorical什么?

And*_*den 62

您可以使用该astype方法来转换Series(一列):

df['col_name'] = df['col_name'].astype(object)
Run Code Online (Sandbox Code Playgroud)

或者整个DataFrame:

df = df.astype(object)
Run Code Online (Sandbox Code Playgroud)

更新

从版本0.15开始,您可以在Series /列中使用category数据类型:

df['col_name'] = df['col_name'].astype('category')
Run Code Online (Sandbox Code Playgroud)

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


her*_*rfz 12

FactorCategorical据我所知,它们是相同的.我认为它最初被称为因子,然后改为分类.要转换为Categorical,你可以使用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
Run Code Online (Sandbox Code Playgroud)

  • 请注意,上述用法已被弃用,需要使用如下:`pd.Categorical(df.b).codes` (2认同)

pig*_*box 10

还有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
Run Code Online (Sandbox Code Playgroud)