python - 将行复制并附加到数据框中,并将时间戳列增加一分钟
问题描述
这是我拥有的数据框:
df = pd.DataFrame([[pd.Timestamp(2017, 1, 1, 12, 32, 0), 2, 3],
[pd.Timestamp(2017, 1, 2, 12, 32, 0), 4, 9]],
columns=['time', 'feature1', 'feature2'])
对于 df 中找到的每个时间戳值(即“时间”列的每个值),我需要再追加5 行,每行的时间列值连续增加一分钟,而其余列值将是照原样复制。
所以输出看起来像:
time feature1 feature2
2017-01-01 12:32:00 2 3
2017-01-01 12:33:00 2 3
2017-01-01 12:34:00 2 3
2017-01-01 12:35:00 2 3
2017-01-01 12:36:00 2 3
2017-01-01 12:37:00 2 3
2017-01-02 12:32:00 4 9
2017-01-02 12:33:00 4 9
2017-01-02 12:34:00 4 9
2017-01-02 12:35:00 4 9
2017-01-02 12:36:00 4 9
2017-01-02 12:37:00 4 9
作为一个优雅的解决方案,我使用了 df.asfreq('1min') 函数。但我不能告诉它在追加 5 行后停止!相反,它将继续以 1 分钟的增量追加行,直到达到下一个时间戳!
我在 python 中尝试了旧的 for 循环,正如预期的那样,它非常耗时(我正在处理 1000 万行)
我希望对此有一个优雅的解决方案?使用诸如“df.asfreq('1min')”之类的函数但在附加 5 行后具有停止条件的东西。
欢迎任何想法!
解决方案
您可以重复 df 然后使用 cumcount 进行 groupby 并添加如下所示的分钟数:
out = df.loc[df.index.repeat(6)]
out['time'] = out['time'] + pd.to_timedelta(out.groupby("time").cumcount(),unit='m')
print(out)
time feature1 feature2
0 2017-01-01 12:32:00 2 3
1 2017-01-01 12:33:00 2 3
2 2017-01-01 12:34:00 2 3
3 2017-01-01 12:35:00 2 3
4 2017-01-01 12:36:00 2 3
5 2017-01-01 12:37:00 2 3
6 2017-01-02 12:32:00 4 9
7 2017-01-02 12:33:00 4 9
8 2017-01-02 12:34:00 4 9
9 2017-01-02 12:35:00 4 9
10 2017-01-02 12:36:00 4 9
11 2017-01-02 12:37:00 4 9
推荐阅读
- swift - 注销后重新登录时应用程序冻结 - firebase
- c++ - 为什么我的程序打不开WAV文件?
- go - 将我的 HTML 链接到 Go Lang
- c# - CSLA.NET 重写 LoadProperty
- zebra-printers - 添加字体时TB不换行
- android - 任务程序类型已存在的执行错误
- python - pygame秒表和定义一个盒子
- java - AssertEquals 不起作用
- javascript - 使用 html 5 视频标签以角度播放本地视频时清理不安全的 URL
- node.js - 从 node.js 应用程序调用 aws lambda 函数会出现 AccessDeniedException 错误