[英]Intersection of rows of a Dataframe based on the value in a column in the dataframe
我有一個 df ,如下所示。 我正在嘗試根據主機列的值查找行的交集。
host values
test ['A','B','C','D']
test ['D','E','B','F']
prod ['1','2','A','D','E']
prod []
prod ['2']
如果主機值相同,則預期的 output 是一行與下一行的交集。 對於上述 df,output 將是
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
並做set
s 的交集。
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] [] []
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.