Pandas 合并行并求和值?
我有一些地震数据。我有我关心的幅度、距离和百分比。我想将所有幅度分组在一起,并对每个幅度的距离和百分比求和。这是我的数据的一部分:
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
我的想法是这样的。 Groupby 和 sum:
df2 = df.groupby(['Distance','Magnitude','Percent'],as_index=False).agg({'Percent': 'sum'},{'Distance': 'sum'})
我在运行代码时得到相同的数据帧,除了它按距离上升,这很好,但没有任何组合或求和。
我希望它看起来像这样:
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
每个震级只有 1 个值,并且每个震级的距离和百分比已求和。
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. 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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这将完成任务,您只需要按幅度进行分组
输出
或者为了防止幅度成为按照@lsr729的索引,您也可以使用它
输出2
This will do the the task, you just need to groupby magnitude only
Output
Or to prevent Magnitude becoming an index as per @lsr729 you can use this as well
Output2