将行复制并附加到数据框,并以一分钟为时间戳列的增量

Copying and appending rows to a dataframe with increment to timestamp column by a minute

这是我的数据框:

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 中找到的每个时间戳值(即对于 'time' 列的每个值),我需要附加 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

您可以使用 pandas.date_rangeexplode 该列上的 DataFrame 创建一个包含所需时间列表的列:

df["time"] = df["time"].apply(lambda x: pd.date_range(start=x, periods=6, freq="1min"))
df = df.explode("time")

>>> df
                 time  feature1  feature2
0 2017-01-01 12:32:00         2         3
0 2017-01-01 12:33:00         2         3
0 2017-01-01 12:34:00         2         3
0 2017-01-01 12:35:00         2         3
0 2017-01-01 12:36:00         2         3
0 2017-01-01 12:37:00         2         3
1 2017-01-02 12:32:00         4         9
1 2017-01-02 12:33:00         4         9
1 2017-01-02 12:34:00         4         9
1 2017-01-02 12:35:00         4         9
1 2017-01-02 12:36:00         4         9
1 2017-01-02 12:37:00         4         9