gpt4 book ai didi

python - 测试 pandas DataFrame 的多列中是否存在共享值

转载 作者:太空宇宙 更新时间:2023-11-03 14:10:10 26 4
gpt4 key购买 nike

如何测试 pandas DataFrame 的多列中是否存在共享值?例如,这样就可以了:

      A    B    C
0 aaa fff lll
1 bbb ggg mmm
2 ccc hhh nnn
3 ddd iii ooo
4 eee jjj ppp

但这不是

      A    B    C
0 aaa fff lll
1 bbb ggg mmm
2 ccc hhh nnn
3 ddd iii bbb
4 eee jjj ppp

因为 bbb 存在于多个列(A 和 C)中。

最佳答案

首先获取所有列组合之间的交集,转换为 numpy 数组,然后转换为 boolean 并测试至少一个 True:

from itertools import combinations
a = [set(df[i[0]]) & set(df[i[1]]) for i in combinations(df.columns,2)]
b = np.array(a).astype(bool).any()

对于第一个 df:

print (a)
[set(), set(), set()]

print (b)
False

对于第二个 df:

print (a)
[set(), {'bbb'}, set()]

print (b)
True

有关更多信息,可以使用(未​​经测试):

d = {i:set(df[i[0]]) & set(df[i[1]]) for i in combinations(df.columns,2)}

s = pd.Series(d)

s = s[s.astype(bool)]

关于python - 测试 pandas DataFrame 的多列中是否存在共享值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48566790/

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