我可以通过编写for循环来解决我的任务,但是我想知道如何以更可笑的方式做到这一点。
因此,我有一个存储某些列表的数据框,并希望找到这些列表中具有任何公共值的所有行,
(此代码仅用于获取具有列表的df:
>>> df = pd.DataFrame( {'a':['A','A','B','B','B','C'], 'b':[1,2,5,1,4,6]})
>>> df
a b
0 A 1
1 A 2
2 B 5
3 B 1
4 B 4
5 C 6
>>> d = df.groupby('a')['b'].apply(list)
)
从这里开始:
>>> d
A [1, 2]
B [5, 1, 4]
C [6]
Name: b, dtype: object
我想选择索引为“ A”和“ B”的行,因为它们的列表重叠值1。
我现在可以编写一个for循环或在这些列表中扩展数据框(与上面的方法相反),并且有多行复制其他值。
你会在这里做什么?还是有某种方法可以使用df.groupby(by = lambda x,y:不返回set(x).isdisjoint(y))比较两个行?
但是groupby和布尔掩码只是一次查看一个元素...
我现在尝试重载列表的相等运算符,并且由于列表不可散列,因此会重载元组和集合(我将散列设置为1以避免身份比较)。然后,我使用了groupby并将其与框架合并,但是看起来,它检查了索引,它已经匹配了。
import pandas as pd
import numpy as np
from operator import itemgetter
class IndexTuple(set):
def __hash__(self):
#print(hash(str(self)))
return hash(1)
def __eq__(self, other):
#print("eq ")
is_equal = not set(self).isdisjoint(other)
return is_equal
l = IndexTuple((1,7))
l1 = IndexTuple((4, 7))
print (l == l1)
df = pd.DataFrame(np.random.randint(low=0, high=4, size=(10, 2)), columns=['a','b']).reset_index()
d = df.groupby('a')['b'].apply(IndexTuple).to_frame().reset_index()
print (d)
print (d.groupby('b').b.apply(list))
print (d.merge (d, on = 'b', how = 'outer'))
输出(对于第一个元素,它工作正常,但是在
[{3}]
处应该有[{3},{0,3}]
代替:True
a b
0 0 {1}
1 1 {0, 2}
2 2 {3}
3 3 {0, 3}
b
{1} [{1}]
{0, 2} [{0, 2}, {0, 3}]
{3} [{3}]
Name: b, dtype: object
a_x b a_y
0 0 {1} 0
1 1 {0, 2} 1
2 1 {0, 2} 3
3 3 {0, 3} 1
4 3 {0, 3} 3
5 2 {3} 2
最佳答案
在merge
上使用df
:
v = df.merge(df, on='b')
common_cols = set(
np.sort(v.iloc[:, [0, -1]].query('a_x != a_y'), axis=1).ravel()
)
common_cols
{'A', 'B'}
现在,预过滤并调用
groupby
:df[df.a.isin(common_cols)].groupby('a').b.apply(list)
a
A [1, 2]
B [5, 1, 4]
Name: b, dtype: object