如何根据列值作为持续时间转换为时间序列



我有每个操作的时间戳和持续时间的数据。我想将数据转换为1分钟时间序列,并根据持续时间列填充行,并在不连续时留下其他行NaN。数据:

datetime           action  duration
2022-01-01 00:00      3      40
2022-01-01 00:40      1      10
2022-01-01 02:34      5      50

期望结果:

datetime           action  duration
2022-01-01 00:00      3      40
2022-01-01 00:01      3      40
...
2022-01-01 00:39      3      40
2022-01-01 00:40      1      10
...
2022-01-01 00:49      1      10
2022-01-01 00:50      NaN    NaN
2022-01-01 00:51      NaN    NaN
...
2022-01-01 02:34      5      50
2022-01-01 02:35      5      50

我试过:df.resample("1min").fillna("pad"),但它用最新的输入填充了中间时间。动作项应根据持续时间填写,然后留下NaN。

我怎样才能做到这一点?

尝试只更新pandas数据帧索引频率

df = df.asfreq('60S')

这将更新datetime索引,并在没有值的地方自动生成nan。无需填充

try this:

tmp = df.copy()
tmp['datetime'] = tmp.apply(lambda x: pd.date_range(
x[0], periods=x[-1], freq='1min'), axis=1)
tmp = tmp.explode('datetime').set_index('datetime')
df['datetime'] = pd.to_datetime(df['datetime'])
df = df.set_index('datetime')
df[:] = float('nan')
res = df.resample(rule='1min').ffill().combine_first(tmp)
print(res)

最新更新