gpt4 book ai didi

python - 在更新 pandas 中的另一列时合并行

转载 作者:行者123 更新时间:2023-12-01 02:33:40 25 4
gpt4 key购买 nike

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  weight0      2      6       11      2      7       12      2      7       13      2      8       14      2     15       15      2     15       16      2     15       17      2     15       1

Option 1 : groupby sum

df.groupby(['node1','node2']).sum().reset_index()
  node1  node2  weight0      2      6       11      2      7       22      2      8       13      2     15       4

Option 2 Pivot table with agg func as sum

df.pivot_table(index=['node1','node2'],aggfunc=sum).reset_index()
    node1  node2  weight0      2      6       11      2      7       22      2      8       13      2     15       4

If you want group occurance more the once then use filter first then groupby sum i.e

ndf = df.groupby(['node1','node2']).filter(lambda x : len(x) > 1)
ndf = ndf.groupby(['node1','node2']).sum().reset_index()
   node1  node2  weight0      2      7       21      2     15       4

Or

ndf = df.groupby(['node1','node2']).sum().reset_index()
ndf[ndf['weight'].ne(1)]

关于python - 在更新 pandas 中的另一列时合并行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46501538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com