1 回答

TA貢獻1826條經驗 獲得超6個贊
說明:
繼續groupby將pid相同的內容分為pid不同的組。在每個組上,應用以下操作:
_ 召集diff各組。diff返回整數或NaN指示 2 個連續行之間的差異。每組的第一行沒有前一行,因此diff始終返回NaN每組的第一行:
df.groupby('pid').total_sum.transform(lambda x: x.diff()
Out[120]:
0 NaN
1 -4.0
2 NaN
3 -3.0
4 -2.0
5 0.0
6 -1.0
7 NaN
8 -4.0
9 0.0
Name: total_sum, dtype: float64
_ne檢查是否有任何值不是0。它返回True不0
df.groupby('pid').total_sum.transform(lambda x: x.diff().ne(0))
Out[121]:
0 True
1 True
2 True
3 True
4 True
5 False
6 True
7 True
8 True
9 False
Name: total_sum, dtype: bool
_cumsum是逐行相加的累積和。在 Python 中,True被解釋為1并被False解釋為0。每組的第一個總是True,因此cumsum總是從1每行開始并將其相加以獲得所需的輸出。
df.groupby('pid').total_sum.transform(lambda x: x.diff().ne(0).cumsum())
Out[122]:
0 1
1 2
2 1
3 2
4 3
5 3
6 4
7 1
8 2
9 2
Name: total_sum, dtype: int32
將所有命令鏈接到一行,如下所示:
df['pos'] = df.groupby('pid').total_sum.transform(lambda x: x.diff().ne(0).cumsum())
Out[99]:
total_sum pid pos
0 5 2 1
1 1 2 2
2 6 7 1
3 3 7 2
4 1 7 3
5 1 7 3
6 0 7 4
7 5 10 1
8 1 10 2
9 1 10 2
- 1 回答
- 0 關注
- 195 瀏覽
添加回答
舉報