我想將以下資料幀從分鐘聚合到 10 分鐘。我一直在嘗試使用 resample 但我意識到我正在丟失另一列。有可能避免這種情況嗎?我猜這也涉及某種分組?
Dataframe 看起來像這樣,其中 date_time 是索引,之后是 name 列和 count 列。
date_time name count
2022-06-03 17:00:00 LoveToKnow 165
2022-06-03 17:00:00 Investing Channel 176
2022-06-03 17:00:00 D17 14
2022-06-03 17:00:00 IFLScience 58
2022-06-03 17:00:00 MotherJones 1
.................
2022-06-03 17:01:00 LoveToKnow 100
2022-06-03 17:01:00 Investing Channel 15
2022-06-03 17:01:00 D17 1
2022-06-03 17:01:00 IFLScience 5
2022-06-03 17:01:00 MotherJones 1
.................
如果我要執行如下所示的重新采樣,它將對值進行分組并對它們求和,但在此程序中我會丟失名稱列。
df.resample('10min').agg({'count': 'sum'}) or
df.resample('10min').sum()
date_time count
2022-06-03 17:00:00 81816
2022-06-03 17:10:00 77504
2022-06-03 17:20:00 73605
2022-06-03 17:30:00 70994
2022-06-03 17:40:00 68658
我期望的輸出應該如下:
date_time name count
2022-06-03 17:00:00 LoveToKnow 1200
2022-06-03 17:00:00 Investing Channel 125
2022-06-03 17:00:00 D17 300
2022-06-03 17:00:00 IFLScience 900
2022-06-03 17:00:00 MotherJones 8
............
2022-06-03 17:10:00 LoveToKnow 700
2022-06-03 17:10:00 Investing Channel 25
2022-06-03 17:10:00 D17 400
2022-06-03 17:10:00 IFLScience 400
2022-06-03 17:10:00 MotherJones 80
.....
uj5u.com熱心網友回復:
name我認為您需要使用 withDataFrame.resample進行分組sum:
df1 = df.groupby('name').resample('10min').sum().swaplevel(1,0).reset_index()
print (df1)
date_time name count
0 2022-06-03 17:00:00 D17 15
1 2022-06-03 17:00:00 IFLScience 63
2 2022-06-03 17:00:00 Investing Channel 191
3 2022-06-03 17:00:00 LoveToKnow 265
4 2022-06-03 17:00:00 MotherJones 2
或解決方案Grouper:
df1 = df.groupby([pd.Grouper(freq='10Min'), 'name']).sum().reset_index()
print (df1)
date_time name count
0 2022-06-03 17:00:00 D17 15
1 2022-06-03 17:00:00 IFLScience 63
2 2022-06-03 17:00:00 Investing Channel 191
3 2022-06-03 17:00:00 LoveToKnow 265
4 2022-06-03 17:00:00 MotherJones 2
如果name每 10 分鐘只需要第一次輸出不同:
df2 = df.resample('10min').agg({'name': 'first', 'count': 'sum'})
print (df2)
name count
date_time
2022-06-03 17:00:00 LoveToKnow 536
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/488328.html
下一篇:根據值在熊貓中創建條件列
