首页 > 解决方案 > Pandas 按分类间隔过滤

问题描述

我创建了一个数据框并将一列分类为间隔:

df_test = pd.DataFrame({'col': [0,1,2,3,4,5,6]})
df_test['cat']= pd.cut(df_test['col'],[-1.,0.,3.,10.])
df_test

        col     cat
    0   0   (-1.0, 0.0]
    1   1   (0.0, 3.0]
    2   2   (0.0, 3.0]
    3   3   (0.0, 3.0]
    4   4   (3.0, 10.0]
    5   5   (3.0, 10.0]
    6   6   (3.0, 10.0]

现在我想使用 cat 列过滤这个数据框:

df_test[df_test['cat'] == pd.Interval(left=1., right=2.)]

    col     cat
1   1   (0.0, 3.0]
2   2   (0.0, 3.0]
3   3   (0.0, 3.0]

为什么用 (1., 2.] 检查相等性会产生这个结果?我期待得到一个空结果,因为数据框中不存在该间隔。

我应该使用不同的方法进行过滤吗?

标签: pythonpandas

解决方案


对于精确匹配,可以使用 hack 解决方案 - 将两者都转换为字符串:

a = df_test[df_test['cat'].astype(str) == str(pd.Interval(left=1., right=2.))]

或使用apply

a = df_test[df_test['cat'].apply(lambda x: x == pd.Interval(left=1., right=2.))]
print (a)
Empty DataFrame
Columns: [col, cat]
Index: []

为什么要为检查成员身份实施此操作的更多信息是here


推荐阅读