簡體   English   中英

在與另一列Pandas中的唯一值相關聯的列中查找值的交集

[英]Finding intersection of values in a column associated with unique values in another column Pandas

如果我有一個像這樣的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')

另一個解決方案:

print df.pivot_table(index="col1", columns="col2", aggfunc=len)
col2    1    2    3    4
col1                    
a     1.0  1.0  NaN  NaN
b     1.0  1.0  NaN  1.0
c     1.0  1.0  1.0  NaN

ser = (df.pivot_table(index="col1", columns="col2", aggfunc=len) == 1).all()
print  ser.index[ser]
Int64Index([1, 2], dtype='int64', name=u'col2')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM