【问题标题】:How do i convert a weighted edglist in Python to a general edgelist?如何将 Python 中的加权边缘列表转换为一般边缘列表?
【发布时间】:2019-07-19 10:57:12
【问题描述】:

我有一个加权的数据边缘列表。它由连接的源、目标和权重组成。像这样:

  source destination  weight
0      A           B       3
1      A           C       2
2      A           D       3

我希望它采用不包含重量值的通用格式。原因是我使用的应用程序没有考虑数据集中的权重值。像这样:

  source destination
0      A           B
1      A           B
2      A           B
3      A           C
4      A           C
5      A           D
6      A           D
7      A           D

我尝试过使用reset_index()unstack(),但得到的结果与我需要的完全不同。 有什么建议吗?

【问题讨论】:

  • 指定你使用的python包。
  • 还包括您尝试过的任何代码,以便我们可以重复它
  • 当前存储的数据是为了什么。那是pandas DataFrame,还是别的什么?
  • 我正在使用熊猫数据框

标签: python pandas edge-list


【解决方案1】:

您可以使用pd.Index.repeat() 并传递weight 列以获得该重复次数,然后在df.loc[] 下调用:

df.loc[df.index.repeat(df.weight),['source','destination']].reset_index(drop=True)

np.repeat() 的替代代码:

final=(pd.DataFrame(np.repeat(df[['source','destination']].values,
  df.weight,axis=0),columns=['source','destination']))

  source destination
0      A           B
1      A           B
2      A           B
3      A           C
4      A           C
5      A           D
6      A           D
7      A           D

【讨论】:

    【解决方案2】:

    使用生成器功能巧妙地完成。为简单起见,假设数据是 3 元组(源、目标、权重)的列表。

    def weighted_to_general(edges):
        for source, destination, weight in edges:
            # Memory optimization: store the tuple only once
            source_destination = (source, destination)
            for n in range(weight):
                yield source_destination
    
    
    data = [
        ('A', 'B', 3),
        ('A', 'C', 2),
        ('B', 'D', 3),
    ]
    
    for source_destination in weighted_to_general(data):
        print(source_destination)
    

    如果您需要一个列表,只需使用 list() 迭代生成器:

    general_data = list(weighted_to_general(data))
    

    【讨论】:

    • 上面的代码对我有用。如果我想从 csv 文件中读取数据怎么办?
    • 使用任何您想将 CSV 文件读入 3 元组列表的方法。这真的超出了这个问题的范围。
    【解决方案3】:

    你可以试试:

    df = pd.DataFrame({'source': ['A', 'A', 'B'], 'destination': ['B', 'C', 'D'], 'weight': [3, 2, 3]})
    
    result = list()
    for index, row in df.iterrows():
        for x in range(row.weight):
            result.append([row.source, row.destination])
    print(pd.DataFrame(result, columns=['source', 'destination']))
    

    结果:

      source destination
    0      A           B
    1      A           B
    2      A           B
    3      A           C
    4      A           C
    5      B           D
    6      B           D
    7      B           D
    

    【讨论】:

    • 上面的代码对我有用。如果我想从 csv 文件中读取数据怎么办?
    • 可以用pandas读取csv文件:df = pd.read_csv('file_name.csv')
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    • 2020-08-19
    • 1970-01-01
    • 2014-09-04
    • 1970-01-01
    相关资源
    最近更新 更多