尋找用于在列布林值之間對行進行分組的 Pandas 語法。
資料表
| 距離 | 時間 | 新的 |
|---|---|---|
| 0 | 2020-10-11 1:30:15 | 真的 |
| 5 | 2020-10-11 1:31:15 | 錯誤的 |
| 10 | 2020-10-11 1:32:15 | 錯誤的 |
| 1 | 2020-10-11 2:30:15 | 真的 |
| 2 | 2020-10-11 2:31:15 | 錯誤的 |
| 30 | 2020-10-11 2:32:15 | 錯誤的 |
| 31 | 2020-10-11 2:33:15 | 錯誤的 |
| 0 | 2020-10-12 1:31:15 | 真的 |
| 5 | 2020-10-12 1:32:15 | 錯誤的 |
題
希望對屬于每個活動的所有行進行分組。新活動由新列中的真實值確定。根據上面的資料,應該有3組。每個組都需要從第一行 True 開始,并在下一個 True 之前以最后一個 False 結束。如何使用groupby?
代碼
這是groupby按日期使用和分組的能力,但就像我上面說的那樣,我希望將其更改為按“新”列分組行到活動中。不過,我打算在這樣的 for 回圈中使用。
for idx, day in df.groupby(df.timestamp.dt.date):
print(idx)
print(day)
uj5u.com熱心網友回復:
只需分組df['new'].cumsum():
for idx, day in df.groupby(df['new'].cumsum()):
print('-----')
print(idx)
print(day)
輸出:
-----
1
distance time new
0 0 2020-10-11 1:30:15 True
1 5 2020-10-11 1:31:15 False
2 10 2020-10-11 1:32:15 False
-----
2
distance time new
3 1 2020-10-11 2:30:15 True
4 2 2020-10-11 2:31:15 False
5 30 2020-10-11 2:32:15 False
6 31 2020-10-11 2:33:15 False
-----
3
distance time new
7 0 2020-10-12 1:31:15 True
8 5 2020-10-12 1:32:15 False
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/362532.html
