You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中将加权边列表(weighted edgelist)转换为普通边列表?

解决方案:将加权边列表转换为重复的普通边列表

嘿,我明白你要做的事了——把带权重的边列表转换成按权重重复对应边的普通列表对吧?你之前用reset_index()和unstack()没得到想要的结果很正常,因为这俩方法的定位是重塑数据结构,不是用来重复行的~下面给你两个简单的pandas解决方案:

方法一:使用repeat()(最直接高效)

这个方法利用DataFrame的索引重复功能,根据weight列的值来复制对应行,然后整理格式即可:

import pandas as pd

# 先构造你的示例数据(假设是DataFrame格式)
df = pd.DataFrame({
    'source': [0, 1, 2],
    'destination': ['A', 'A', 'A'],
    'target': ['B', 'C', 'D'],
    'weight': [3, 2, 3]
})

# 核心步骤:按weight值重复每一行,然后重置索引、去掉weight列
result = df.loc[df.index.repeat(df['weight'])]  # 重复行
result = result.drop(columns=['weight']).reset_index(drop=True)  # 清理格式

# 给新的source列重新编号(匹配你要的输出格式)
result['source'] = result.index

print(result)

运行后就能得到你想要的输出:

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

方法二:使用explode()(更直观的逻辑)

如果你更喜欢分步拆解的逻辑,可以先把weight转换成对应长度的列表,再用explode()展开:

import pandas as pd

df = pd.DataFrame({
    'source': [0, 1, 2],
    'destination': ['A', 'A', 'A'],
    'target': ['B', 'C', 'D'],
    'weight': [3, 2, 3]
})

# 给每行生成一个长度等于weight的临时列表
df['temp'] = df['weight'].apply(lambda x: [1]*x)
# 展开临时列表,相当于重复行
result = df.explode('temp')
# 清理不需要的列并重置索引
result = result.drop(columns=['weight', 'temp']).reset_index(drop=True)
# 重新编号source列
result['source'] = result.index

print(result)

为什么reset_index()和unstack()不行?

  • unstack()是用来把层级索引的行转换为列,属于数据重塑操作,和重复行完全不相关;
  • reset_index()只是用来把索引转换为列或者重置索引值,单独用它也没法实现行重复的需求。

内容的提问来源于stack exchange,提问作者Taie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:06:35