我有看起来像这样的数据框(frame_combined_DF(。我需要根据为每个 SKU 提供的 Time_W 周进行自定义重新采样。
frame_combined_DF
SKU Qty Time Time_W
WY
2011-10-17 ABC 12.0 11.0 2
2012-01-16 ABC 20.0 11.0 2
2013-04-08 ABC 6.0 11.0 2
2013-12-02 ABC 2.0 11.0 2
2014-10-27 XYZ 1.0 21.0 3
下面是我的代码
for i in ids:
subset = frame_combined_DF.loc[frame_combined_DF.SKU==i]
subset.index=subset.WY
subset.sort_index(inplace=True)
period=subset.Time_W.unique().astype('int64')[0]
per=str(period)+'W'
df = subset.Qty.resample(per).sum()
new_df = {'WY':df.index, 'Qty':df.values,'SKU':i}
newdf = pd.DataFrame(new_df)
new_series=new_series.append(newdf)
我在运行此代码时收到以下错误
ValueError: Offset <0 * Weeks: weekday=6> did not increment date
预期输出如下。以下示例仅适用于 1 个 SKU。此 SKU 需要以 2 周的频率重新采样,其中 SKU XYZ 需要每 3 周重新采样一次
WY Qty SKU
2011-10-17 12.0 ABC
2011-10-31 0.0 ABC
2011-11-14 0.0 ABC
2011-11-28 0.0 ABC
2011-12-12 0.0 ABC
.........................
.........................
2012-01-09 20.0 ABC
2012-01-23 0.0 ABC
..........................
从您的示例数据中,我看到WY是索引列。
但是检查此列是否为日期时间类型(不是字符串(。 如果不是,请运行frame_combined_DF.index = pd.to_datetime(frame_combined_DF.index)
。
需要注意的另一点是,newdf是一个数据帧,而不是一个系列, 因此,应将其附加到数据帧。
第三个评论是subset.index = subset。不需要 WY,因为WY已经是指数。
最后一件事:您的样本没有定义new_series(在我的解决方案中( 我将其更改为结果(。
因此,请将您的代码更改为:
result = pd.DataFrame()
for i in frame_combined_DF.SKU.unique():
subset = frame_combined_DF.loc[frame_combined_DF.SKU==i]
subset.sort_index(inplace=True)
period = subset.Time_W.unique().astype('int64')[0]
per = str(period) + 'W'
df = subset.Qty.resample(per).sum()
new_df = {'WY': df.index, 'Qty': df.values, 'SKU': i}
newdf = pd.DataFrame(new_df)
result = result.append(newdf, ignore_index=True)
它应该运行,至少在我的计算机上它没有错误。