我有每個操作的時間戳和持續時間的資料。我想將資料轉換為 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。
我怎樣才能做到這一點?
uj5u.com熱心網友回復:
嘗試這個:
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)
uj5u.com熱心網友回復:
嘗試僅更新 pandas 資料幀索引頻率
df = df.asfreq('60S')
這應該會更新日期時間索引并在不存在值的地方自動引入 NaN。無需填充。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/532877.html
