简体   繁体   English

Pandas 合并行和求和值?

[英]Pandas Merging rows and summing values?

I have some earthquake data.我有一些地震数据。 I have a Magnitude, Distance, and Percent that I care about.我有一个我关心的幅度、距离和百分比。 I want to group all of the MAGNITUDES together and sum the distances and percents for each magnitudes.我想将所有 MAGNITUDES 组合在一起,并对每个星等的距离和百分比求和 Here is a part of my data:这是我的一部分数据:

import pandas as pd

data = {'Distance': [1, 5, 9, 3, 5, 4, 2, 3.1],
        'Magnitude': [7.3, 7.3, 7.3, 6.0, 8.2, 6.0, 8.2, 5.7],
        'Percent': [0.1, 0.05, 0.07, 0.11, 0.2, 0.07, 0.08,0.11]
       }

df = pd.DataFrame(data)

print(df)


         Distance  Magnitude  Percent
 0       1.0        7.3     0.10
 1       5.0        7.3     0.05
 2       9.0        7.3     0.07
 3       3.0        6.0     0.11
 4       5.0        8.2     0.20
 5       4.0        6.0     0.07
 6       2.0        8.2     0.08
 7       3.1        5.7     0.11

My idea was this.我的想法是这样的。 Groupby and sum:分组和求和:

df2 = df.groupby(['Distance','Magnitude','Percent'],as_index=False).agg({'Percent': 'sum'},{'Distance': 'sum'})

I get the same dataframe upon running my code except it is ascending by distance which is fine, but nothing groupped together or summed.我在运行我的代码时得到相同的 dataframe 除了它按距离递增这很好,但没有组合在一起或求和。

I want it to look like this:我希望它看起来像这样:

       Distance  Magnitude  Percent
0      15.0        5.7     0.22
1       7.0        6.0     0.18
2       7.0        7.3     0.28
3       3.1        8.2     0.11

There is only 1 value for each magnitude and the distances and percents have been summed for each magnitude.每个震级只有 1 个值,并且已将每个震级的距离和百分比相加。

This will do the the task, you just need to groupby magnitude only这将完成任务,您只需要按幅度分组

df.groupby(by=["Magnitude"]).sum()

Output Output

           Distance  Percent
Magnitude                   
5.7             3.1     0.11
6.0             7.0     0.18
7.3            15.0     0.22
8.2             7.0     0.28


Or to prevent Magnitude becoming an index as per @lsr729 you can use this as well或者为了防止 Magnitude 成为 @lsr729 的索引,您也可以使用它

df.groupby(by=["Magnitude"], as_index=False).sum()

Output2输出2

   Magnitude  Distance  Percent
0        5.7       3.1     0.11
1        6.0       7.0     0.18
2        7.3      15.0     0.22
3        8.2       7.0     0.28

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM