【问题标题】:pandas astype categories not working熊猫 astype 类别不起作用
【发布时间】:2016-10-23 10:57:41
【问题描述】:

我厌倦了使用来自 http://pandas.pydata.org/pandas-docs/stable/categorical.html 的文档将列更改为 catgeory

df = pd.DataFrame({'A':[1,2,3,4,5], 'B':['a','b','c','d','e'], 'C':['A','B','A','B','A']})
df['C']=df['C'].astype('category')

如果我尝试通过类别

df['C']=df['C'].astype('category',categories=['A','B'])

说错了

TypeError: _astype() got an unexpected keyword argument 'categories'

将类别传递给astype() 的正确方法是什么?

【问题讨论】:

  • 如果我同时运行 df['C']=df['C'].astype('category')df['C']=df['C'].astype('category',categories=['A','B']),我会遇到与您相同的错误。但是,如果我在初始化 DataFrame 后只运行 df['C']=df['C'].astype('category',categories=['A','B']),我不会收到任何错误。
  • 我在这两个语句中都没有看到错误。
  • @root,你的 pandas 和 numpy 版本是什么?
  • @MaxU:pandas 0.18.1 和 numpy 1.11.0
  • 我猜这是一个 numpy v. 1.10.4,它不知道这个论点......

标签: pandas


【解决方案1】:

您现在需要通过 CategorialDtype 传入它,因为 astype 方法不再接受它们

from pandas.api.types import CategoricalDtype
df = pd.DataFrame({'A':[1,2,3,4,5], 'B':['a','b','c','d','e'], 'C':['A','B','A','B','A']})
df['C']=df['C'].astype(CategoricalDtype(categories=['A','B']))

【讨论】:

    【解决方案2】:

    分类也适用。

    myCategory = ['A','B']
    df['C'] = pd.Categorical(df['C'], categories=myCategory, ordered=True)
    

    【讨论】:

      猜你喜欢
      • 2017-05-24
      • 1970-01-01
      • 2015-12-24
      • 2019-04-21
      • 2017-11-23
      • 1970-01-01
      • 2018-03-11
      • 2016-07-14
      相关资源
      最近更新 更多