【问题标题】:Resample time series data重新采样时间序列数据
【发布时间】:2020-03-03 02:14:46
【问题描述】:

我有一些随机的每小时时间序列数据,(让我们弥补一些)我如何为每日最大值重新采样以及为记录的每日最大值的小时创建一个单独的 df 列?

import pandas as pd 
import numpy as np 
from numpy.random import randint
import os

np.random.seed(10)  # added for reproductibility                                                                                                                                                                 

rng = pd.date_range('10/9/2018 00:00', periods=1000, freq='1H') 
df = pd.DataFrame({'Random_Number':randint(1, 100, 1000)}, index=rng)

df.index.name = 'Date'

重新采样随机值:

daily_summary = pd.DataFrame()

daily_summary['Random_Number_Resamp'] = df['Random_Number'].resample('D').max()


daily_summary.head()

然后尝试记录每日最大值发生的小时数...

daily_summary['Hour_Map'] = daily_summary.Random_Number_Resamp.index.strftime('%H').astype('int')

daily_summary

上面的代码不会抛出属性错误,但是hour_map会是零。。当daily_summary df被创建时,hour_map也出现在这一步,我该如何完成?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    你可以做groupby:

    df.groupby(df.index.normalize())['Random_Number'].agg(['idxmax', 'max']) 
    

    输出(头部):

                             idxmax     max
    Date        
    2018-10-09  2018-10-09 05:00:00     94
    2018-10-10  2018-10-10 20:00:00     95
    2018-10-11  2018-10-11 15:00:00     97
    2018-10-12  2018-10-12 18:00:00     98
    2018-10-13  2018-10-13 22:00:00     91
    

    【讨论】:

    • 感谢您的提示...规范化有什么作用?我还得研究聚合的​​作用
    • 它一直截断到 00:00:00。这里的聚合只是将每个函数应用于组。当然它可以做得更多。
    • 是否可以将idxmax max 列更改为仅将小时表示为整数?
    • new_df['hour'] = new_df['idxmax'].dt.hour?
    • 出于某种原因,这给了我一个关键错误KeyError: 'idxmax'
    【解决方案2】:

    我想我明白你在寻找什么......

    只需在原始 df 中创建一个小时列,然后重新采样:

    np.random.seed(10)  # added for reproductibility                                                                                                                                                                 
    
    rng = pd.date_range('10/9/2018 00:00', periods=1000, freq='1H') 
    df = pd.DataFrame({'Random_Number':randint(1, 100, 1000)}, index=rng)
    
    df.index.name = 'Date'
    
    # create hour column
    df['hour'] = df.index.hour
    
    # resample df
    daily_summary = df.resample('D').max()
    
                Random_Number  hour
    Date                           
    2018-10-09             94    23
    2018-10-10             95    23
    2018-10-11             97    23
    2018-10-12             98    23
    2018-10-13             91    23
    

    【讨论】:

      猜你喜欢
      • 2014-12-15
      • 1970-01-01
      • 2020-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-18
      • 2020-05-18
      • 1970-01-01
      相关资源
      最近更新 更多