将多个列转换为Pandas中的类别。申请?

2024-04-27 00:30:27 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑一个数据帧。我想将一组列to_convert转换为类别。

我当然可以做到以下几点:

for col in to_convert:
  df[col] = df[col].astype('category')

但我很惊讶,下面没有返回数据帧:

df[to_convert].apply(lambda x: x.astype('category'), axis=0)

当然,这会导致以下情况不起作用:

df[to_convert] = df[to_convert].apply(lambda x: x.astype('category'), axis=0)

为什么^{}axis=0)返回一个序列,即使它应该逐个作用于列?


Tags: to数据lambdainconvertdffor情况
2条回答

这只是在master中修复的,在0.17.0中也会修复,请参见问题here

In [7]: df = DataFrame({'A' : list('aabbcd'), 'B' : list('ffghhe')})

In [8]: df
Out[8]: 
   A  B
0  a  f
1  a  f
2  b  g
3  b  h
4  c  h
5  d  e

In [9]: df.dtypes
Out[9]: 
A    object
B    object
dtype: object

In [10]: df.apply(lambda x: x.astype('category'))       
Out[10]: 
   A  B
0  a  f
1  a  f
2  b  g
3  b  h
4  c  h
5  d  e

In [11]: df.apply(lambda x: x.astype('category')).dtypes
Out[11]: 
A    category
B    category
dtype: object

注意since pandas 0.23.0您不再apply将多个列转换为分类数据类型。现在您只需执行df[to_convert].astype('category')(其中to_convert是问题中定义的一组列)。

相关问题 更多 >