2024-04-24 16:02:30 发布
网友
node1 node2 weight 2 6 1 2 7 1 2 7 1 2 8 1 2 15 1 2 15 1 2 15 1 2 15 1
从上面可以看出,我想合并node1==node2的行,并在满足此条件的地方更新权重,这样就只有一行具有唯一的节点1和节点2,并且权重是相等条件的不出现
示例输出为:
node 1 node 2 weight 2 7 2 2 15 4
等等
如果你有这样的数据帧
node1 node2 weight 0 2 6 1 1 2 7 1 2 2 7 1 3 2 8 1 4 2 15 1 5 2 15 1 6 2 15 1 7 2 15 1
选项1:按总和分组
df.groupby(['node1','node2']).sum().reset_index()
node1 node2 weight 0 2 6 1 1 2 7 2 2 2 8 1 3 2 15 4
选项2以agg func作为和的透视表
df.pivot_table(index=['node1','node2'],aggfunc=sum).reset_index()
如果您希望组发生一次以上,则首先使用筛选器,然后使用groupby sum,即
ndf = df.groupby(['node1','node2']).filter(lambda x : len(x) > 1) ndf = ndf.groupby(['node1','node2']).sum().reset_index()
node1 node2 weight 0 2 7 2 1 2 15 4
或者
ndf = df.groupby(['node1','node2']).sum().reset_index() ndf[ndf['weight'].ne(1)]
如果你有这样的数据帧
选项1:按总和分组
选项2以agg func作为和的透视表
如果您希望组发生一次以上,则首先使用筛选器,然后使用groupby sum,即
或者
相关问题 更多 >
编程相关推荐