jss*_*ssm 3 python group-by sum pandas
我有一个DataFrame看起来像
A B
0 1.2 1
1 1.2 6
2 1.2 4
3 2.3 2
4 2.3 5
5 1.2 7
Run Code Online (Sandbox Code Playgroud)
我希望获得一组具有相同价值的部分金额,A但前提是它们彼此相邻.对于这种情况,我希望另一个DataFrame像
0 1.2 11
3 2.3 7
5 1.2 7
Run Code Online (Sandbox Code Playgroud)
我有一种感觉,我可以使用,.groupby但我只能管理它无视这些群体A是否彼此相邻.
使用groupby由助手Series用骨料first和sum:
df = df.groupby(df.A.ne(df.A.shift()).cumsum(), as_index=False).agg({'A':'first','B':'sum'})
print (df)
A B
0 1.2 11
1 2.3 7
2 1.2 7
Run Code Online (Sandbox Code Playgroud)
细节:
将shiftd列与ne(!=)进行比较,并cumsum为连续组添加Series:
print (df.A.ne(df.A.shift()).cumsum())
0 1
1 1
2 1
3 2
4 2
5 3
Name: A, dtype: int32
Run Code Online (Sandbox Code Playgroud)
感谢@ user2285236的评论:
当dtype为float时,检查相等性可能会导致不需要的结果.np.isclose可能是更好的选择
df = df.groupby(np.cumsum(~np.isclose(df.A, df.A.shift())), as_index=False).agg({'A':'first','B':'sum'})
print (df)
A B
0 1.2 11
1 2.3 7
2 1.2 7
print (np.cumsum(~np.isclose(df.A, df.A.shift())))
[1 1 1 2 2 3]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
257 次 |
| 最近记录: |