pandas - 多列标题中跨多列的 Pandas 索引子句
问题描述
我有一个带有多列标题的数据框。
import pandas as pd
headers = pd.MultiIndex.from_tuples([("A", "u"), ("A", "v"), ("B", "x"), ("B", "y")])
f = pd.DataFrame([[1, 1, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1], [1, 0, 1, 0]], columns = headers)
f
A B
u v x y
0 1 1 0 1
1 1 0 0 0
2 0 0 1 1
3 1 0 1 0
我想选择所有 A 列或所有 B 列都为真的行。我可以明确地这样做。
f[f["A"]["u"].astype(bool) | f["A"]["v"].astype(bool)]
A B
u v x y
0 1 1 0 1
1 1 0 0 0
3 1 0 1 0
f[f["B"]["x"].astype(bool) | f["B"]["y"].astype(bool)]
A B
u v x y
0 1 1 0 1
2 0 0 1 1
3 1 0 1 0
我想编写一个函数select(f, top_level_name)
,其中索引子句适用于同一顶级名称下的所有列,这样
select(f, "A") == f[f["A"]["u"].astype(bool) | f["A"]["v"].astype(bool)]
select(f, "B") == f[f["B"]["x"].astype(bool) | f["B"]["y"].astype(bool)]
我希望这个函数可以处理任意数量的具有任意名称的子列。
我该怎么写select
?
解决方案
推荐阅读
- intellij-idea - IntelliJ Webstorm 终端颜色错误
- python - PyImport_ImportModule 之后如何最终清理?
- google-admin-sdk - Google Meet 审核日志 - 未经验证用户的 IP
- solr - 如何恢复 solr 碎片
- python-3.x - 将元组中的元组转换为列表中的列表
- corda - RHEL 上的 Corda Kubernetes 部署
- kubernetes - 升级连接 10.96.0.1:443 时出错:I/o 超时
- pyspark - 重命名由于 partitionBy 而创建的文件夹
- javascript - 如何在带有服务器端的reactjs中添加反应分页
- consul - connect 不能作为 consul 的命令使用