不定期重新取样

问题描述 投票:0回答:2

我有一个定期间隔的时间序列存储在pandas数据框中:

1998-01-01 00:00:00 5.71

1998-01-01 12:00:00 5.73

1998-01-02 00:00:00 5.68

1998-01-02 12:00:00 5.69 ...

我还有一个不规则间隔的日期列表:

1998-01-01

1998-07-05

1998-09-21 ....

我想计算日期列表的每个时间间隔之间的时间序列的平均值。这是否可以使用pandas.DataFrame.resample?如果没有,最简单的方法是什么?

编辑:例如,计算“日期”中日期之间的“系列”的平均值,由以下代码创建:

import pandas as pd
import numpy as np
import datetime

rng = pd.date_range('1998-01-01', periods=365, freq='D')
series = pd.DataFrame(np.random.randn(len(rng)), index=rng)

dates = [pd.Timestamp('1998-01-01'), pd.Timestamp('1998-07-05'), pd.Timestamp('1998-09-21')]
python python-3.x pandas numpy datetime
2个回答
0
投票

您可以遍历日期并使用仅选择落在这些日期之间的行,如下所示,

import pandas as pd
import numpy as np
import datetime

rng = pd.date_range('1998-01-01', periods=365, freq='D')
series = pd.DataFrame(np.random.randn(len(rng)), index=rng)

dates = [pd.Timestamp('1998-01-01'), pd.Timestamp('1998-07-05'), pd.Timestamp('1998-09-21')]

for i in range(len(dates)-1):

    start = dates[i]
    end = dates[i+1]

    sample = series.loc[(series.index > start) & (series.index <= end)]

    print(f'Mean value between {start} and {end} : {sample.mean()[0]}')

# Output
Mean value between 1998-01-01 00:00:00 and 1998-07-05 00:00:00 : -0.024342221543215112
Mean value between 1998-07-05 00:00:00 and 1998-09-21 00:00:00 : 0.13945008064765074

您也可以使用这样的列表理解而不是循环,

[series.loc[(series.index > dates[i]) & (series.index <= dates[i+1])].mean()[0] for i in range(len(dates) - 1) ] # [-0.024342221543215112, 0.13945008064765074]

0
投票

您可以像这样迭代日期:

for ti in range(1,len(dates)):
    start_date,end_date=dates[ti-1],dates[ti]
    mask=(series.index > start_date) & (series.index <= end_date)
    print(series[mask].mean())
© www.soinside.com 2019 - 2024. All rights reserved.