Python 将dataframe转换为元组列表,并将唯一的整数对作为第一个条目
我有以下数据帧:Python 将dataframe转换为元组列表,并将唯一的整数对作为第一个条目,python,python-3.x,pandas,dataframe,tuples,Python,Python 3.x,Pandas,Dataframe,Tuples,我有以下数据帧: 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,
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”列的整数的唯一组合,第二个条目应该是设置为1的权重。使用itertools中的组合,然后通过解压缩组合并添加{'weight':1}来形成所需的元组
使用itertools中的组合,然后通过解压缩组合并添加{'weight':1}来形成所需的元组
你没有问过类似的问题吗@QuangHoang是的,我问过,但我自己做不到-对这一切都比较陌生,这一切都有点让人不知所措…你没有问过类似的问题吗@QuangHoang是的,我问过,但我自己做不到-对这一切都比较陌生,这一切都有点让人不知所措。。。
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})]