【问题标题】:convert pandas dataframe to list of tuple with unique pairs of integers as the first entry将 pandas 数据框转换为具有唯一整数对的元组列表作为第一个条目
【发布时间】:2021-01-15 04:38:52
【问题描述】:

我有以下数据框:

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

【问题讨论】:

  • 你不是问过类似的问题吗before
  • @QuangHoang 是的,我做到了,但我自己做不到——对这一切来说相对较新,这一切都让人不知所措......

标签: python python-3.x pandas dataframe tuples


【解决方案1】:

使用itertools 中的combinations,然后通过解压缩组合并添加您的{'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})]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-13
    • 2020-04-13
    • 2020-12-13
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    相关资源
    最近更新 更多