python - 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.] 检查相等性会产生这个结果?我期待得到一个空结果,因为数据框中不存在该间隔。
我应该使用不同的方法进行过滤吗?
解决方案
对于精确匹配,可以使用 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
推荐阅读
- bash - Bash 忽略命令行参数中的引号
- google-apps-script - 谷歌应用脚本从工作表更新表单
- flutter - Flutter-我如何从登录屏幕切换到主页和返回?后端工作但不手动刷新无法显示屏幕
- jenkins - Jenkins 流水线脚本中的当前工作目录
- awk - 从列表中的字符串中提取所有数字
- react-admin - 通过 dataprovider 加载数据后的 react-admin 原始状态
- javascript - 创建一个按钮以将多个类添加到多个按钮并在单击重置时将其删除
- javascript - 如果在地图内其他
- javascript - 一起使用 jQuery Pan 和 Zoomooz 来平移和缩放 DOM 元素
- javascript - ' ' 字符串文字包含未转义的换行错误