将 pandas 数据帧转换为元组列表,其中唯一的整数对作为第一个条目

我有以下数据框:


    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 的权重。


白猪掌柜的
浏览 47回答 1
1回答

慕神8447489

使用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})]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python