无法按分类列过滤pandas数据帧

时间:2015-06-17 07:52:44

标签: python pandas

pandas 0.16.1 我将数据帧中的所有列转换为分类,因此在转储到磁盘时占用的空间会减少很多。现在我想过滤数据帧。对于==和.isin没关系,但是<,< =等等的操作失败。"无序分类的操作只能比较是否相等"

data[data["MONTH COLUMN"]<=3]

如果我在categorical.py中注释掉以下几行,一切正常。它是熊猫中的一个错误吗?

if not self.ordered:
    if op in ['__lt__', '__gt__','__le__','__ge__']:
        raise TypeError("Unordered Categoricals can only compare equality or not")

我认为在列上使用Categorical数据类型是个好主意,该列在〜1&#39; 400&#39; 000行中只有12个唯一值。)

1 个答案:

答案 0 :(得分:4)

documentation州:

  

注意不会自动订购新的分类数据。您必须明确传递ordered = True以表示已订购的分类。

首次创建要订购的类别时,只需指定:

In [1]: import pandas as pd

In [3]: s = pd.Series(["a","b","c","a"]).astype('category', ordered=True)

In [5]: s
Out[5]: 
0    a
1    b
2    c
3    a
dtype: category
Categories (3, object): [a < b < c]

In [4]: s > 'a'
Out[4]: 
0    False
1     True
2     True
3    False
dtype: bool
相关问题