我的資料如下所示:
print(df)
DateTime, Status
'2021-09-01', 0
'2021-09-05', 1
'2021-09-07', 0
我需要它看起來像這樣:
print(df_desired)
DateTime, Status
'2021-09-01', 0
'2021-09-02', 0
'2021-09-03', 0
'2021-09-04', 0
'2021-09-05', 1
'2021-09-06', 1
'2021-09-07', 0
現在我使用這樣的熊貓來完成這個:
new_index = pd.DataFrame(index = pd.date_range(df.index[0], df.index[-1], freq='D'))
df = new_index.join(df).ffill()
使用該列中第一條記錄的倒數來估算任何列中第一條記錄之前的缺失值,因為它是二進制的,并且只顯示變化點,這保證是正確的。
據我了解,我想要的資料框包含“連續”資料,但我不確定在源資料中如何呼叫資料結構。
問題:
當我對頻率為每秒一條記錄的資料幀執行此操作并且我想加載一年的資料時,我的記憶體溢位(需要 92GB,可用約 60GB)。我不確定是否有標準程式而不是我的解決方案,我不知道名稱并且無法使用谷歌找到,或者我使用的 join 方法錯誤,但這似乎效率低下,結果資料幀是此操作后只有幾百兆位元組。對此的任何反饋都會很棒!
uj5u.com熱心網友回復:
您可以使用此管道:
(df.set_index('DateTime')
.reindex(pd.date_range(df['DateTime'].min(), df['DateTime'].max()))
.rename_axis('DateTime')
.ffill(downcast='infer')
.reset_index()
)
輸出:
DateTime Status
0 2021-09-01 0
1 2021-09-02 0
2 2021-09-03 0
3 2021-09-04 0
4 2021-09-05 1
5 2021-09-06 1
6 2021-09-07 0
輸入:
DateTime Status
0 2021-09-01 0
1 2021-09-05 1
2 2021-09-07 0
uj5u.com熱心網友回復:
使用DataFrame.asfreq與DatetimeIndex:
df = df.set_index('DateTime').asfreq('d', method='ffill').reset_index()
print (df)
DateTime Status
0 2021-09-01 0
1 2021-09-02 0
2 2021-09-03 0
3 2021-09-04 0
4 2021-09-05 1
5 2021-09-06 1
6 2021-09-07 0
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/315260.html
