我有一个通用格式的数据帧:
id,transaction_dt,units,measures
1,2018-01-01,4,30.5
1,2018-01-03,4,26.3
2,2018-01-01,3,12.7
2,2018-01-03,3,8.8 我正在尝试完成的是基于同一记录中的'transaction_dt‘字段的值来堆叠和枚举'units’,并将它们展开到新的记录中,以产生如下所示的结果:
id,transaction_dt,measures
1,2018-01-01,30.5
1,2018-01-02,30.5
1,2018-01-03,30.5
1,2018-01-04,30.5
1,2018-01-03,26.3
1,2018-01-04,26.3
1,2018-01-05,26.3
1,2018-01-06,26.3
2,2018-01-01,12.7
2,2018-01-02,12.7
2,2018-01-03,12.7
2,2018-01-03,8.8
2,2018-01-04,8.8
2,2018-01-05,8.8 我一直在努力为我之前问题的答案创建一个矢量化的性能版本,有人在这里友好地回答了这个问题:Python PANDAS: Stack and Enumerate Date to Create New Records
df.set_index('transaction_dt', inplace=True)
df.apply(lambda x: pd.Series(pd.date_range(x.name, periods=x.units)), axis=1). \
stack(). \
reset_index(level=1). \
join(df['measure']). \
drop('level_1', axis=1). \
reset_index(). \
rename(columns={0:'enumerated_dt'}) 这确实可以工作,但我有一个非常大的数据集来运行它,所以我需要投资来优化它。他建议创建一个包含所有日期的数组,我可以这样做:
date_range = pd.date_range('2004-01-01', '2017-12-31', freq='1D')他建议对数组进行重新索引,并以某种方式向前填充值。如果有人能帮助我,我将由衷感谢!
发布于 2018-02-10 01:47:45
可以按列对重复索引使用numpy.repeat,对重复行使用loc。最后,根据每个索引通过cumcount获取count,转换to_timedelta并添加到列transaction_dt。默认唯一索引的最后一个reset_index:
df = df.loc[np.repeat(df.index, df['units'])]
df['transaction_dt'] += pd.to_timedelta(df.groupby(level=0).cumcount(), unit='d')
df = df.reset_index(drop=True)
print (df)
id transaction_dt units measures
0 1 2018-01-01 4 30.5
1 1 2018-01-02 4 30.5
2 1 2018-01-03 4 30.5
3 1 2018-01-04 4 30.5
4 1 2018-01-03 4 26.3
5 1 2018-01-04 4 26.3
6 1 2018-01-05 4 26.3
7 1 2018-01-06 4 26.3
8 2 2018-01-01 3 12.7
9 2 2018-01-02 3 12.7
10 2 2018-01-03 3 12.7
11 2 2018-01-03 3 8.8
12 2 2018-01-04 3 8.8
13 2 2018-01-05 3 8.8https://stackoverflow.com/questions/48711305
复制相似问题