[英]How can I aggregate rows together according to a selected column using a pandas DataFrame
[英]How I can group timestamp column to hourly and aggregate the rows in pandas dataframe
我有一個包含每分鍾數據的數據框,它還包含一個date
列,用於以時間戳格式跟蹤日期。
在這里,我試圖按小時而不是分鍾來聚合數據。
我嘗試了以下正在運行的代碼,但它需要根據我不想要的date
列進行索引,因為這樣我就無法使用df.loc
函數遍歷數據幀。
import pandas as pd
from datetime import datetime
import numpy as np
date_rng = pd.date_range(start='1/1/2018', end='1/08/2018', freq='T')
df = pd.DataFrame(date_rng, columns=['date'])
df['data'] = np.random.randint(0,100,size=(len(date_rng)))
df.set_index('date')
df.index = pd.to_datetime(df.index, unit='s')
df = df.resample('H').sum()
df.head(15)
我也嘗試過 groupby 但它不起作用,以下是代碼。
df.groupby([df.date.dt.hour]).data.sum()
print(df.head(15))
如何在不索引的情況下按date
分組?
謝謝。
嘗試pd.Grouper
並指定freq
參數:
df.groupby([pd.Grouper(key='date', freq='1H')]).sum()
完整代碼:
import pandas as pd
from datetime import datetime
import numpy as np
date_rng = pd.date_range(start='1/1/2018', end='1/08/2018', freq='T')
df = pd.DataFrame(date_rng, columns=['date'])
df['data'] = np.random.randint(0, 100, size=(len(date_rng)))
print(df.groupby([pd.Grouper(key='date', freq='1H')]).sum())
# data
# date
# 2018-01-01 00:00:00 2958
# 2018-01-01 01:00:00 3084
# 2018-01-01 02:00:00 2991
# 2018-01-01 03:00:00 3021
# 2018-01-01 04:00:00 2894
# ... ...
# 2018-01-07 20:00:00 2863
# 2018-01-07 21:00:00 2850
# 2018-01-07 22:00:00 2823
# 2018-01-07 23:00:00 2805
# 2018-01-08 00:00:00 25
# [169 rows x 1 columns]
希望有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.