首页 > 解决方案 > 多列标题中跨多列的 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

标签: pandasmulti-index

解决方案


推荐阅读