尝试将每周8个时间点的样本下调到2个点,每个时间点代表4周的平均值,我使用resample()。我开始使用(60 * 60 * 24 * 7 * 4)秒定义规则,看到我最终得到3个时间点,最新的一个是假的。开始检查它,我注意到如果我将规则定义为4W或28D它没关系,但是下降到672H或更小的单位(分钟,秒,......),会出现额外的伪造列。这个测试代码:
import numpy as np
import pandas as pd
d = np.arange(16).reshape(2, 8)
res = []
for month in range(1,13):
start_date = str(month) + '/1/2014'
df = pd.DataFrame(data=d, index=['A', 'B'], columns=pd.date_range(start_date, periods=8, freq='7D'))
print(df, '\n')
dfw = df.resample(rule='4W', how='mean', axis=1, closed='left', label='left')
print('4 Weeks:\n', dfw, '\n')
dfd = df.resample(rule='28D', how='mean', axis=1, closed='left', label='left')
print('28 Days:\n', dfd, '\n')
dfh = df.resample(rule='672H', how='mean', axis=1, closed='left', label='left')
print('672 Hours:\n', dfh, '\n')
dfm = df.resample(rule='40320T', how='mean', axis=1, closed='left', label='left')
print('40320 Minutes:\n', dfm, '\n')
dfs = df.resample(rule='2419200S', how='mean', axis=1, closed='left', label='left')
print('2419200 Seconds:\n', dfs, '\n')
res.append(([start_date], dfh.shape[1] == dfd.shape[1]))
print('\n\n--------------------------\n\n')
[print(res[i]) for i in range(12)]
pass
打印为(我这里只粘贴了最后一次迭代的打印输出):
2014-11-01 2014-11-29 2014-12-27
A 1.5 5.5 NaN
B 9.5 13.5 NaN
2014-12-01 2014-12-08 2014-12-15 2014-12-22 2014-12-29 2015-01-05 \
A 0 1 2 3 4 5
B 8 9 10 11 12 13
2015-01-12 2015-01-19
A 6 7
B 14 15
4 Weeks:
2014-11-30 2014-12-28
A 1.5 5.5
B 9.5 13.5
28 Days:
2014-12-01 2014-12-29
A 1.5 5.5
B 9.5 13.5
672 Hours:
2014-12-01 2014-12-29 2015-01-26
A 1.5 5.5 NaN
B 9.5 13.5 NaN
40320 Minutes:
2014-12-01 2014-12-29 2015-01-26
A 1.5 5.5 NaN
B 9.5 13.5 NaN
2419200 Seconds:
2014-12-01 2014-12-29 2015-01-26
A 1.5 5.5 NaN
B 9.5 13.5 NaN
--------------------------
(['1/1/2014'], False)
(['2/1/2014'], True)
(['3/1/2014'], True)
(['4/1/2014'], True)
(['5/1/2014'], False)
(['6/1/2014'], False)
(['7/1/2014'], False)
(['8/1/2014'], False)
(['9/1/2014'], False)
(['10/1/2014'], False)
(['11/1/2014'], False)
(['12/1/2014'], False)
因此,date_range在9个月开始时出错,3个月(2月至4月)没有错误。不管是错过了什么,还是错误,是吗?
答案 0 :(得分:1)
谢谢@DSM和@Andy,确实我有大熊猫0.15.1,升级到最新的0.15.2解决了它