我有下面的 Pandas(版本 0.15.2)数据框。我想在创建 df
之后将 code
列设为 Categorical
类型的有序变量,如下所示。
import pandas as pd
df = pd.DataFrame({'id' : range(1,9),
'code' : ['one', 'one', 'two', 'three',
'two', 'three', 'one', 'two'],
'amount' : np.random.randn(8)}, columns= ['id','code','amount'])
df.code = df.code.astype('category')
>> 0 one
>> 1 one
>> 2 two
>> 3 three
>> 4 two
>> 5 three
>> 6 one
>> 7 two
>> Name: code, dtype: category
>> Categories (3, object): [one < three < two]
所以这有效,但只是部分有效。我不能强加命令。以下所有功能均在 documentation webpage 上进行了演示,为我抛出语法错误:
df.code = df.code.astype('category', categories=['one','two','three'], ordered=True)
>> error: astype() got an unexpected keyword argument 'categories'
或者甚至:
df.code.ordered
>> error: 'Series' object has no attribute 'ordered'
df.code.categories
>> error: 'Series' object has no attribute 'categories'
1) 这很烦人。我什至无法获取我的 Categorical
变量的类别(级别)。我是否做错了什么或者网络文档是否已过时/不一致?
2) 另外,你知道类型 Categorical
是否有距离概念,即 Pandas 是否知道根据上面的排序,one
比 two
更接近 two
?我计划用它来计算(不)相似性。
最佳答案
这是一个简短的示例,其中包含有序分类变量和(对我来说)使用 rank()
(作为一种距离度量)得出的令人惊讶的结果:
df = pd.DataFrame({ 'code':['one','two','three','one'], 'num':[1,2,3,1] })
df.code = df.code.astype('category', categories=['one','two','three'], ordered=True)
code num
0 one 1
1 two 2
2 three 3
3 one 1
df.sort('code')
code num
0 one 1
3 one 1
1 two 2
2 three 3
因此 sort()
按指定的顺序按预期工作。但是 rank()
并没有按照我的猜测进行操作,它按字典顺序排名并忽略分类变量的顺序。
df.sort('code').rank()
code num
0 1.5 1.5
3 1.5 1.5
1 4.0 3.0
2 3.0 4.0
所有这些可能是一个更长的提问方式:也许您只想要一个整数类型?我的意思是,你可以在排序后在这里编写某种距离函数,但最终这将比你使用标准 int 或 float 所做的工作要多得多(如果你看看如何 rank()
处理有序分类。
编辑添加:上面的部分内容可能不适用于 pandas 15.2,但我相信您仍然可以这样做来指定顺序:
df['code'].cat.categories = ['one','two','three']
默认情况下(据我所知)在 15.2 中发生的情况是,ordered 默认情况下为 True(但在版本 16.0 中为 False),但顺序将按字典顺序排列,而不是按构造函数中指定的顺序排列。但我不确定,并且我正在 16.0 中工作,因此您必须观察您的版本的行为方式。请记住,分类仍然是相当新的......
关于python - Pandas 分类数据类型的行为不符合预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29829427/