为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

白猪掌柜的 2023-09-19 14:33:02
我有以下数据框:    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})]


查看完整回答
反对 回复 2023-09-19
  • 1 回答
  • 0 关注
  • 46 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信