I have the following dataframe:
ID weight
0 2 1
1 3 1
2 4 1
3 5 1
4 6 1
5 7 1
My goals is to generate a list of tuples that looks like this:
[(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})....]
Each entry should be a unique combination of integers from the 'ID'column
and the second entry should just be a weight set to 1.
Use combinations
from itertools
, then form the desired tuple by unpacking the combination and adding your {'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})]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.