This is the closest to what i'm looking for that I've found计数行与大熊猫GROUPBY内连续日期
比方说,我的数据框看起来是这样的:
d = {'item_number':['K208UL','AKD098008','DF900A','K208UL','AKD098008']
'Comp_ID':['998798098','988797387','12398787','998798098','988797387']
'date':['2016-11-12','2016-11-13','2016-11-17','2016-11-13','2016-11-14']}
df = pd.DataFrame(data=d)
我想算在同一item_number
和Comp_ID
观察中的倍量连续多日。
我想这会看起来沿着线:
g = df.groupby(['Comp_ID','item_number'])
g.apply(lambda x: x.loc[x.iloc[i,'date'].shift(-1) - x.iloc[i,'date'] == 1].count())
不过,我需要比较,这些我还遇到的麻烦之前,提取每个日期为int的一天。
for i in df.index:
wbc_seven.iloc[i, 'day_column'] = datetime.datetime.strptime(df.iloc[i,'date'],'%Y-%m-%d').day
显然基于位置的索引只允许整数?我怎么能解决这个问题?
我得到这个错误:TypeError:不支持的操作数类型为 - :'str'和'str' –
显然,您需要将'date'列转换为'Timestamp'类型。在分组之前,使用此[连续['日期'] = pd.to_datetime(连续['日期'])''。我也会在答案中进行编辑。 – Kartik
太棒了!从我的第一轮质量保证看起来,这个工作很好。我并没有想象中那么遥远。如果你可以添加一些关于你的代码中发生的事情的解释,我会非常感激。 @Kartik –