【问题标题】:Converting multiple columns to categories in Pandas. apply?在 Pandas 中将多列转换为类别。申请?
【发布时间】:2019-11-05 14:16:44
【问题描述】:

考虑一个数据框。我想将一组列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)

为什么apply (axis=0) 会返回一个 Series,即使它应该逐列作用?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    这只是在 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
    

    【讨论】:

      【解决方案2】:

      请注意,since pandas 0.23.0 您不再使用apply 将多个列转换为分类数据类型。现在您可以简单地改用df[to_convert].astype('category')(其中to_convert 是问题中定义的一组列)。

      【讨论】:

      • 看起来这里需要一行来作为一个完整的例子:to_convert = ['parks', 'playgrounds', 'sports', 'roading']; df[to_convert] = df[to_convert].astype('category')
      • @VickiB to_convert 是问题中的一组列,添加该行以澄清。
      • 这就是我的想法(附上我的评论)
      猜你喜欢
      • 2017-02-15
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多