有点难以解释,但请尽我所能,请忍受我。
我有一个ID,发货日期和单位的Pd。
我想计算3天内的发货量,并且该计数不应重叠,例如我的数据帧如下。
ID Shipping Date Units Expected output
153131151007 20180801 1 1
153131151007 20180828 1 2
153131151007 20180829 1 0
153131151007 20180904 1 1
153131151007 20181226 2 4
153131151007 20181227 1 0
153131151007 20181228 1 0
153131151007 20190110 1 1
153131151007 20190115 2 3
153131151007 20190116 1 0
153131151011* 20180510 1 2
153131151011* 20180511 1 0
153131151011* 20180513 1 2
153131151011* 20180515 1 0
153131151011* 20180813 1 1
153131151011* 20180822 1 2
153131151011* 20180824 1 0
153131151011* 20190103 1 1
该代码应检查日期,看看接下来3天内是否有货,如果有货,则应在其当前日期栏中将其加总,并确保不考虑用于下一个日期计算的总计数。
因此,对于第一个ID运送日期20181226,它将检查1226、1227、1228并将它们加在一起并在1226中显示结果,然后在接下来的2个单元格中显示0。
同样,对于第二个ID 20180510,0510是该系列中发货的第一个日期。它检查0510、0511和0512并将其求和到0510中,然后将其余部分清零,这就是为什么0511不考虑0513并将其作为其他装运组的一部分的原因。
data = pd.DataFrame({'ID':['153131151007','153131151007','153131151007','153131151007','153131151007','153131151007','153131151007','153131151007','153131151007','153131151007','153131151011*','153131151011*','153131151011*','153131151011*','153131151011*','153131151011*','153131151011*','153131151011*'],
'Date':[20180801,20180828,20180829,20180904,20181226,20181227,20181228,20190110,20190115,20190116,20180510,20180511,20180513,20180515,20180813,20180822,20180824,20190103],
'Units':[1,1,1,1,2,1,1,1,2,1,1,1,1,1,1,1,1,1]})
最佳答案
这可以工作,但是结果采用宽格式:
import pandas as pd
import numpy as np
from dateutil.parser import parse
from datetime import timedelta
data = pd.DataFrame({'ID':['153131151007','153131151007','153131151007','153131151007','153131151007','153131151007','153131151007','153131151007','153131151007','153131151007','153131151011*','153131151011*','153131151011*','153131151011*','153131151011*','153131151011*','153131151011*','153131151011*'],
'Date':[20180801,20180828,20180829,20180904,20181226,20181227,20181228,20190110,20190115,20190116,20180510,20180511,20180513,20180515,20180813,20180822,20180824,20190103],
'Units':[1,1,1,1,2,1,1,1,2,1,1,1,1,1,1,1,1,1]})
def keep_first(ser):
ixs = []
ts = ser.dropna().index[0]
while ts <= ser.dropna().index.max():
if ts in ser.dropna().index:
ixs.append(ts)
ts+=timedelta(3)
else:
ts+=timedelta(1)
return np.where(ser.index.isin(ixs), ser, 0)
data['Date'] = data['Date'].map(lambda x: parse(str(x))) # parse dates
units = data.groupby(['ID', 'Date']).sum().unstack(0).resample('D').sum() # create resampled units df
units = units.sort_index(ascending=False).rolling(3, min_periods=1).sum().sort_index() # calculate forward-rolling sum
grouped_ix = data.groupby(['ID', 'Date']).sum().unstack(0).index # get indices for actual data
units.loc[grouped_ix].apply(keep_first) # get sums for actual data indices, keep only first
关于python - 自从 Pandas 第一次发货以来的3天内累计/累计发货数量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56226784/