在同一组内对列数值求和,然后将该数据框分开保存。

huangapple go评论51阅读模式
英文:

Sum column values within the same group and save that dataframe separately

问题

让我们假设我有一个类似下面的数据框:

value   parent

  23    X
  32    Y
  11    Z

如果我想将这个数据框转换为上述形式,我该怎么做呢?基本上,我是在同一组内对列值进行求和,并将该数据框保存到一个单独的数据框中。正如您所看到的,我对长度列不感兴趣。
英文:

Let's say I have a dataframe that looks like the following:

In [186]:

df = pd.read_csv(file, engine='python',sep='\t')
df

Out[186]:
length value   parent
        
100       5       X
 90      18       X
 77      17       Y
 15      15       Y
 89      11       Z

What do I do if I want to change this datframe into the following:

value   parent
        
  23    X
  32    Y
  11    Z

I am basically summing up the column values within the same group and saving that dataframe into a separate data frame. As you can see, I am not intested in the length column.

答案1

得分: 0

删除长度列并执行以下操作:

df.groupby(['parent']).sum()

文档链接

英文:

drop the length column and do

df.groupby(['parent']).sum()

documentation

huangapple
  • 本文由 发表于 2023年3月7日 05:51:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75656169.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定