假设这是我的 df:
Name1 Name2 date
1 John Jay 2015-01-01 06:01:00
2 Sara Debra 2015-01-01 06:05:00
3 Ben Beth 2015-01-01 06:09:00
我想填写 df,其中每行应重复并增加 1 分钟,直到到达下一行,因此输出应为:
Name1 Name2 date
1 John Jay 2015-01-01 06:01:00
1 John Jay 2015-01-01 06:02:00
1 John Jay 2015-01-01 06:03:00
1 John Jay 2015-01-01 06:04:00
2 Sara Debra 2015-01-01 06:05:00
2 Sara Debra 2015-01-01 06:06:00
3 Ben Beth 2015-01-01 06:07:00
我研究了 date_range,但没有找到一种没有丑陋且低效的 for 循环的正确方法。
如有任何帮助,我们将不胜感激!
最佳答案
如果所有日期时间都是唯一的,您可以使用 DataFrame.asfreq
:
df['date'] = pd.to_datetime(df['date'])
df1 = (df.set_index('date')
.asfreq('Min', method='ffill')
.reset_index().reindex(df.columns, axis=1))
对我来说,解决方案是 DataFrame.resample
使用 DatetimeIndex
和 Resampler.ffill
:
df1 = df.set_index('date').resample('1Min').ffill().reset_index().reindex(df.columns, axis=1)
<小时/>
print (df1)
Name1 Name2 date
0 John Jay 2015-01-01 06:01:00
1 John Jay 2015-01-01 06:02:00
2 John Jay 2015-01-01 06:03:00
3 John Jay 2015-01-01 06:04:00
4 Sara Debra 2015-01-01 06:05:00
5 Sara Debra 2015-01-01 06:06:00
6 Sara Debra 2015-01-01 06:07:00
7 Sara Debra 2015-01-01 06:08:00
8 Ben Beth 2015-01-01 06:09:00
关于python - Pandas - 用日期范围填充数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60395369/