重新采样时间序列数据的多个变量

时间:2020-03-03 14:25:58

标签: python pandas time-series

我有一些时间序列数据(组成一些),一个变量是value,另一个变量是Temperature

import numpy as np
import pandas as pd
np.random.seed(11)

rows,cols = 50000,2
data = np.random.rand(rows,cols) 
tidx = pd.date_range('2019-01-01', periods=rows, freq='T') 
df = pd.DataFrame(data, columns=['Temperature','Value'], index=tidx)

问题 ,我如何每天在名为daily_summary的独立熊猫df中每天对数据进行重采样,每列3列,分别包含:

  1. 每日最大值
  2. 最大值出现的小时
  3. 出现最大值时的记录温度

我知道我可以在下面使用此代码查找每日的最大值和发生的时间:

daily_summary = df.groupby(df.index.normalize())['Value'].agg(['idxmax', 'max']) 
daily_summary['hour'] = daily_summary['idxmax'].dt.hour
daily_summary = daily_summary.drop(['idxmax'], axis=1)
daily_summary.rename(columns = {'max':'DailyMaxValue'}, inplace = True)

但是我迷失了试图记录这些每日最高记录中的温度...

使用.loc是一种更好的方法,其中循环可以每天过滤一次……类似这样的东西?

for idx, days in df.groupby(df.index.date):
    print(days)
    daily_summary = df.loc[days['Value'].max().astype('int')] 

如果运行此命令,我可以每天打印days,但是daily_summary会抛出TypeError: cannot do index indexing on <class 'pandas.core.indexes.datetimes.DatetimeIndex'> with these indexers [0] of <class 'numpy.int32'>

非常感谢任何提示

1 个答案:

答案 0 :(得分:0)

您可以解析为idxmaxloc

idx = df.groupby(df.index.normalize())['Value'].idxmax()
ret_df = df.loc[idx].copy()

# get the hour
ret_df['hour'] = ret_df.index.hour

# set date as index
ret_df.index = ret_df.index.normalize()

输出:

            Temperature     Value  hour
2019-01-01     0.423320  0.998377    19
2019-01-02     0.117154  0.999976    10
2019-01-03     0.712291  0.999497    16
2019-01-04     0.404229  0.999996    21
2019-01-05     0.457618  0.999371    17
相关问题