gpt4 book ai didi

python - Pandas - 检查多索引数据帧的任何索引中是否存在列的值

转载 作者:行者123 更新时间:2023-12-03 08:03:54 24 4
gpt4 key购买 nike

我得到了一个名为 df 的多索引数据帧,它有两个索引(index1、index2)。我想按行搜索以检查列中的值是否存在于任何多索引中。

这就是 df 的样子

                Column
index1 index2
a b b
c e
d c
f e e
g e
h f

就 bool 值而言,这就是我想要生成的值以过滤数据帧

                Column
index1 index2
a b True
c False
d False
f e True
g False
h True (f is in the index1)

最终的输出应该是这样的:

                Column
index1 index2
a b b
f e e
h f

有什么好的做法可以处理这个问题吗?

最佳答案

您可以使用get_level_values:

m1 = df.index.get_level_values('index1') == df['Column']
m2 = df.index.get_level_values('index2') == df['Column']
out = df[m1|m2]
print(out)

# Output
Column
index1 index2
a b b
f e e
h f

通用方式

import numpy as np

out = df[np.logical_or.reduce([list(lvl) == df['Column'] for lvl in zip(*df.index)])]
print(out)

# Output
Column
index1 index2
a b b
f e e
h f

关于python - Pandas - 检查多索引数据帧的任何索引中是否存在列的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73075322/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com