gpt4 book ai didi

python - 在与另一列 Pandas 中的唯一值关联的列中查找值的交集

转载 作者:太空宇宙 更新时间:2023-11-04 00:50:57 26 4
gpt4 key购买 nike

如果我有这样的 DataFrame (非常小的例子)

  col1  col2
0 a 1
1 a 2
2 b 1
3 b 2
4 b 4
5 c 1
6 c 2
7 c 3

并且我希望所有 col2 值与其唯一的 col1 值相关时的交集(所以在这种情况下,交集将是 [1 ,2]), 我怎样才能用 Pandas 做到这一点?另一种说法是 col2 中的值存在于 col1 中的每个唯一值。

我的()解决方案是使用 unique 获取唯一的 col1 元素,然后从 中的每个唯一元素构建字典>col1 然后取这些字典值的集合交集。我觉得我应该使用一种机制将列关联在一起,但这可以使这更容易。

最佳答案

一种方法是使用 pivot_table :

In [11]: cross = df.pivot_table(index="col1", columns="col2", aggfunc='size') == 1

In [12]: cross
Out[12]:
col2 1 2 3 4
col1
a True True False False
b True True False True
c True True True False

In [13]: cross.all()
Out[13]:
col2
1 True
2 True
3 False
4 False
dtype: bool

In [14]: cross.columns[cross.all()]
Out[14]: Int64Index([1, 2], dtype='int64', name='col2')

关于python - 在与另一列 Pandas 中的唯一值关联的列中查找值的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37203156/

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