【发布时间】:2020-02-10 10:14:47
【问题描述】:
我有一个 df,其中每个项目包含一个日期范围的行,我需要将其扩展为每个项目每天包含一行。
看起来像这样:
from to id
1 25/02/2019 27/02/2019 A
2 15/07/2019 16/07/2019 B
我想要这个:
date id
1 25/02/2019 A
2 26/07/2019 A
3 27/07/2019 A
4 15/07/2019 B
5 16/07/2019 B
我设法编写了一个有效的代码,但它需要一个多小时才能运行,所以我想知道是否有更有效的方法来做到这一点。
我的代码:
df_dates = pd.DataFrame()
for i in range(len(df)):
start = df.loc[i]['from']
end = df.loc[i]['to'] + np.timedelta64(1,'D') #includes last day of the range
dates = np.arange(start, end, dtype='datetime64[D]')
temp = pd.DataFrame()
temp = temp.append([df.loc[i]]*len(dates), ignore_index=True)
temp['datadate'] = dates
df_dates = df_dates.append(temp, ignore_index=True)
这需要很长时间,因为实际范围大约是 50 年,有超过 1700 个项目,所以新的 df 很大,但也许你知道一个更快地做同样事情的技巧:)
【问题讨论】:
标签: python pandas for-loop date-range