[英]convert pandas dataframe to list of tuple with unique pairs of integers as the first entry
我有以下数据框:
ID weight
0 2 1
1 3 1
2 4 1
3 5 1
4 6 1
5 7 1
我的目标是生成一个如下所示的元组列表:
[(2,3,{'weight':1}),(2,4,{'weight':1}),(2,5,{'weight':1}),(2,6,{'weight':1}),(2,7,{'weight':1}),(3,4,{'weight':1}),(3,5,{'weight':1}),(3,6,{'weight':1}),(3,7,{'weight':1}),(4,5,{'weight':1})....]
每个条目应该是来自'ID'column
的唯一整数组合,第二个条目应该只是设置为 1 的权重。
使用itertools
combinations
,然后通过解包组合并添加您的{'weight' : 1}
形成所需的元组。
from itertools import combinations
[(*x, {'weight': 1}) for x in combinations(df['ID'], 2)]
[(2, 3, {'weight': 1}),
(2, 4, {'weight': 1}),
(2, 5, {'weight': 1}),
(2, 6, {'weight': 1}),
(2, 7, {'weight': 1}),
(3, 4, {'weight': 1}),
(3, 5, {'weight': 1}),
(3, 6, {'weight': 1}),
(3, 7, {'weight': 1}),
(4, 5, {'weight': 1}),
(4, 6, {'weight': 1}),
(4, 7, {'weight': 1}),
(5, 6, {'weight': 1}),
(5, 7, {'weight': 1}),
(6, 7, {'weight': 1})]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.