我有以下數據框: 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
提交
取消