将多个列转换为Pandas中的类别.应用?

Ame*_*ina 8 python pandas

考虑一个Dataframe.我想将一组列转换to_convert为类别.

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

for col in to_convert:
  df[col] = df[col].astype('category')
Run Code Online (Sandbox Code Playgroud)

但我很惊讶以下不返回数据帧:

df[to_convert].apply(lambda x: x.astype('category'), axis=0)
Run Code Online (Sandbox Code Playgroud)

这当然使以下不起作用:

df[to_convert] = df[to_convert].apply(lambda x: x.astype('category'), axis=0)
Run Code Online (Sandbox Code Playgroud)

为什么apply(axis=0)返回一个系列,即使它应该一个接一个地作用于列?

Jef*_*eff 8

这只是在master中修复,因此将在0.17.0中修复,请参阅此处的问题

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