【问题标题】:resampling and appending to same dataframe重新采样并附加到相同的数据帧
【发布时间】:2021-11-07 05:59:00
【问题描述】:

我有一个数据框,我想对其重新采样并将结果作为新列附加到原始数据框,

我有什么:

index = pd.date_range('1/1/2000', periods=9, freq='T')
series = pd.Series(range(9), index=index)
series

time                 value      
2000-01-01 00:00:00    0
2000-01-01 00:01:00    1
2000-01-01 00:02:00    2
2000-01-01 00:03:00    3
2000-01-01 00:04:00    4
2000-01-01 00:05:00    5
2000-01-01 00:06:00    6
2000-01-01 00:07:00    7
2000-01-01 00:08:00    8

我想要什么:

time                 value   mean_resampled
2000-01-01 00:00:00    0.         2
2000-01-01 00:01:00    1.         NaN
2000-01-01 00:02:00    2.         NaN
2000-01-01 00:03:00    3.         NaN
2000-01-01 00:04:00    4.         NaN         
2000-01-01 00:05:00    5.         6.5
2000-01-01 00:06:00    6.         NaN
2000-01-01 00:07:00    7.         NaN
2000-01-01 00:08:00    8.         NaN

注意:重采样频率为'5T'

【问题讨论】:

  • 重采样的频率是多少?
  • 刚刚修改了问题:)
  • 现在好多了 :) 现在答案就是你所期望的 :)

标签: python pandas pandas-resample


【解决方案1】:

使用resample 计算平均值,使用concatSeries 与新值合并。

>>> pd.concat([series, series.resample('5T').mean()], axis=1) \
      .rename(columns={0: 'value', 1: 'mean_resampled'})

                     value  mean_resampled
2000-01-01 00:00:00      0             2.0
2000-01-01 00:01:00      1             NaN
2000-01-01 00:02:00      2             NaN
2000-01-01 00:03:00      3             NaN
2000-01-01 00:04:00      4             NaN
2000-01-01 00:05:00      5             6.5
2000-01-01 00:06:00      6             NaN
2000-01-01 00:07:00      7             NaN
2000-01-01 00:08:00      8             NaN

如果您的实际情况是DataFrame 而不是Series,您只需添加一个新列:

>>> df['mean_resampled'] = df.resample('5T').mean()

【讨论】:

    【解决方案2】:
    index = pd.date_range('1/1/2000', periods=9, freq='T')
    series = pd.Series(range(9), index=index, name='values')
    
    sample = series.resample('5T').mean() # create a sample at some frequency
    df = series.to_frame() # convert series to frame
    df.loc[sample.index.values, 'mean_resampled'] = sample # use loc to assign new values
    
                         values  mean_resampled
    2000-01-01 00:00:00       0             2.0
    2000-01-01 00:01:00       1             NaN
    2000-01-01 00:02:00       2             NaN
    2000-01-01 00:03:00       3             NaN
    2000-01-01 00:04:00       4             NaN
    2000-01-01 00:05:00       5             6.5
    2000-01-01 00:06:00       6             NaN
    2000-01-01 00:07:00       7             NaN
    2000-01-01 00:08:00       8             NaN
    

    【讨论】:

      猜你喜欢
      • 2017-09-19
      • 2020-11-29
      • 2018-08-26
      • 2018-11-16
      • 1970-01-01
      • 2018-04-17
      • 1970-01-01
      • 2018-09-28
      • 1970-01-01
      相关资源
      最近更新 更多