![](/img/trans.png)
[英]Intersection / union for each set of words in any given two lists python in a for loop
[英]intersection and union set between two lists base on data frame
a = {'A' : [1,2,3,4],
'B' : [[1,4,5,6],[2,3,6],[4,5,6]],
'C' : [[1,4,6],[3,5],[4,10],[10]]
}
基於數據框:如何找到B列和C之間的交集和並集? output 這樣的:
A B C intersect union
0 1 [1,4,5,6] [1,4,6] [1,4,6] [1,4,5,6]
1 2 [2,3,6] [3,5] [3] [2,3,5,6]
2 3 [4,5,6] [4,10] [4] [4,5,6,10]
3 4 [4,5,6] [10] [] [4,5,6,10]
您可以定義一次返回兩個值的自定義 function 並逐行應用該 function。
def func(row):
inters = list(set(row['B']).intersection(row['C']))
uni = list(set(row['B']).union(row['C']))
return inters, uni
a[['intersect', 'union']] = a.apply(func, axis=1, result_type='expand')
print(df)
A B C intersect union
0 1 [1, 4, 5, 6] [1, 4, 6] [1, 4, 6] [1, 4, 5, 6]
1 2 [2, 3, 6] [3, 5] [3] [2, 3, 5, 6]
2 3 [4, 5, 6] [4, 10] [4] [10, 4, 5, 6]
3 4 [4, 5, 6] [10] [] [10, 4, 5, 6]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.