【发布时间】:2021-12-09 08:48:51
【问题描述】:
我有一个反复出现的问题,我每次都无法很好地解决,而且我找不到解决问题的好方法。 假设我有一个索引中包含日期时间的数据框,每 3 小时跨越一次(df1)。我每天都有另一个数据框 (df2)。
我想做两件事:
- 通过计算一天中每 3 小时周期的平均值,对 df1 进行重新采样,使其每天跨越一次,而不是每 3 小时一次。
- 对可能丢失的任何一天插入 df2,并将该天添加到它所属的位置。
问题:我使用 for 循环(并希望避免这种情况)并且缺失天数的重采样不完整(只能属性 1 个值)。
这就是我的做法:
import numpy as np
import pandas as pd
from datetime import *
# Create df1
rng = pd.date_range('2000-01-01', periods=365*(24/3), freq='3H')
df1 = pd.DataFrame({'Val': np.random.randn(len(rng)) }, index = rng)
# Create df2 and drop a few rows
rng2 = pd.date_range('2000-01-01', periods=365, freq='D')
df2 = pd.DataFrame({'Val': np.random.randn(len(rng2)) },index = rng2)
df2 = df2.drop([datetime(2000,1,5),datetime(2000,1,24)])
# Create reference timelist
date_list = [datetime(2000,1,1) + timedelta(days=x) for x in range(365)]
# Calculate the daily mean of df1:
# We create an array hosting the resampled values of df1
arr = []
c = 1
# Loop that appends the array everytime we hit a new day, and calculate a mean of the day that passed
for i in range(1,len(df1)):
if c < 365 and df1.index[i] == date_list[c]:
arr.append(np.mean(df1[i-8:i])[0])
c = c + 1
# Calculate the last value of the array
arr.append(np.mean(df1[i-7:i+1])[0])
# Create a new dataframe hosting the daily values from df1
df3 = pd.DataFrame({'Val': arr}, index = rng2)
# Replace missing days in df2
df2 = df2.reindex(date_list, fill_value=0)
df2 = df2.resample('D').interpolate(method='linear') # but this does not work
【问题讨论】:
标签: python pandas datetime pandas-resample