簡體   English   中英

我如何將時間戳列分組為每小時並聚合熊貓數據框中的行

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM