Python 基于数据帧中列中的值的数据帧行的交集
我有一个df,如下所示。我试图根据主机列的值查找行的交点Python 基于数据帧中列中的值的数据帧行的交集,python,python-3.x,pandas,dataframe,intersection,Python,Python 3.x,Pandas,Dataframe,Intersection,我有一个df,如下所示。我试图根据主机列的值查找行的交点 host values test ['A','B','C','D'] test ['D','E','B','F'] prod ['1','2','A','D','E'] prod [] prod ['2'] 预期的输出是一行和下一行的交点 如果主机值相同。 对于上述df,输出为 test=['B','D'] - intersection of row 1 and 2 prod=[] - inters
host values
test ['A','B','C','D']
test ['D','E','B','F']
prod ['1','2','A','D','E']
prod []
prod ['2']
预期的输出是一行和下一行的交点
如果主机值相同。
对于上述df,输出为
test=['B','D'] - intersection of row 1 and 2
prod=[] - intersection of row 3 and 4
prod=[] - intersection of row 4 and 5
由于主机列值不匹配,因此不会执行第2行和第3行的交集。感谢您的帮助
df.to_dict值为
{'host': {0: 'test', 1: 'test', 2: 'prod', 3: 'prod', 4: 'prod'},
'values': {0: ['A', 'B', 'C', 'D'],
1: ['D', 'E', 'B', 'F'],
2: ['1', '2', 'A', 'D', 'E'],
3: [],
4: ['2']}
}
不确定预期结果的结构,但可以使用shift为每组主机创建一列。然后在新列为notna的位置使用apply,并进行集合相交
df['val_shift'] = df.groupby('host')['values'].shift()
df['intersect'] = df[df['val_shift'].notna()]\
.apply(lambda x: list(set(x['values'])&set(x['val_shift'])), axis=1)
print (df)
host values val_shift intersect
0 test [A, B, C, D] NaN NaN
1 test [D, E, B, F] [A, B, C, D] [B, D]
2 host [1, 2, A, D, E] NaN NaN
3 host [] [1, 2, A, D, E] []
4 host [2] [] []