Python 熊猫:对所有行求和
我有一个Python 熊猫:对所有行求和,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个数据帧,看起来像这样: score num_participants 0 20 1 15 2 5 3 10 4 12 5 15 我需要找到当前行中得分大于或等于得分的参与者人数: score num_participants num_participants_with_score_greater_or_equal 0 20 77 1 15 57 2
数据帧
,看起来像这样:
score num_participants
0 20
1 15
2 5
3 10
4 12
5 15
我需要找到当前行中得分大于或等于得分的参与者人数:
score num_participants num_participants_with_score_greater_or_equal
0 20 77
1 15 57
2 5 42
3 10 37
4 12 27
5 15 15
所以,我试图将当前行和它下面的所有行相加。数据大约有5000行,因此我无法通过索引手动设置它cumsum
不起作用,我不确定是否有简单的方法可以做到这一点。我已经花了相当长的时间试图解决这个问题,因此如果有任何帮助,我将不胜感激。这是一个相反的cumsum
。将列表倒过来,cumsum
,然后倒回去
df.iloc[::-1].cumsum().iloc[::-1]
score num_participants
0 15 77
1 15 57
2 14 42
3 12 37
4 9 27
5 5 15
除非score
已经排序,否则
df['num_participants_with_score_greater_or_equal'] = df.sort_values('score', ascending=False).num_participants.cumsum()
进行评分
的顺序正确。你可以通过.sort_index()
恢复原始顺序。误解了你关于“需要找到得分较低的参与者…”的观点。iloc
在位置索引方面优于ix
,因为ix
很难解释语义。