我有以下数据框: 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 的权重。
1 回答
慕神8447489
TA贡献1780条经验 获得超1个赞
使用combinationsfrom itertools,然后通过解压组合并添加您的 来形成所需的元组{'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})]
添加回答
举报
0/150
提交
取消