gpt4 book ai didi

python - Pandas GroupBy 和组内总和

转载 作者:行者123 更新时间:2023-11-28 22:13:09 25 4
gpt4 key购买 nike

假设我有一个如下所示的数据框:

    interview       longitude        latitude
1 A1 34.2 90.2
2 A1 54.2 23.5
3 A3 32.1 21.5
4 A4 54.3 93.1
5 A2 45.1 29.5
6 A1 NaN NaN
7 A7 NaN NaN
8 A1 NaN NaN
9 A3 23.1 38.2
10 A5 -23.7 -98.4

我希望能够执行某种 groupby 方法,输出每个子组中的总现值。因此,对于这样的事情,期望的输出将是:

    interview         longitude         latitude       occurs 
1 A1 2 2 4
2 A2 1 1 1
3 A3 2 2 2
4 A4 1 1 1
5 A5 1 1 1
6 A7 0 0 1

我尝试使用此命令尝试纬度,但未获得所需的输出:

df.groupby(by=['interview', 'latitude'])['interview'].count()

谢谢!

最佳答案

groupby + sum 之前使用 notna

s1=(df[['**longitude**','**latitude**']].notna()).groupby(df['**interview**']).sum()
s2=df.groupby(df['**interview**']).size()# note size will count the NaN value as well
pd.concat([s1,s2.to_frame('**occurs** ')],axis=1)
Out[115]:
**longitude** **latitude** **occurs**
**interview**
A1 2.0 2.0 4
A2 1.0 1.0 1
A3 2.0 2.0 2
A4 1.0 1.0 1
A5 1.0 1.0 1
A7 0.0 0.0 1

关于python - Pandas GroupBy 和组内总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54185910/

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