我有一個時間序列資料的多索引資料框,如下所示;
A B C
1 1 21 32 4
2 4 2 23
3 12 9 10
4 1 56 37
.
.
.
.
30 63 1 27
31 32 2 32
.
.
.
12 1 2 3 23
2 23 1 12
3 32 3 23
.
.
.
31 23 2 32
它本質上是具有三列的月份和日期的多索引。
我需要將其轉換為每日資料,并且基本上有一個資料框,其中有一個索引,其中上述資料框中的值回應其各自的 10 年日期。
例如;
Desired output;
A B C
01/01/2017 21 32 4
.
.
31/12/2017 23 2 32
.
.
01/01/2022 21 32 4
.
.
31/12/2022 23 2 32
我希望這很清楚!它基本上將每日/每月資料轉換為每日/每月/每年資料。
uj5u.com熱心網友回復:
您可以使用:
df.index = pd.to_datetime(df.index.rename(['month', 'day']).to_frame().assign(year=2022))
輸出:
A B C
2022-01-01 21 32 4
2022-01-02 4 2 23
2022-01-03 12 9 10
2022-01-04 1 56 37
2022-01-30 63 1 27
2022-01-31 32 2 32
2022-12-01 2 3 23
2022-12-02 23 1 12
2022-12-03 32 3 23
2022-12-31 23 2 32
跨越數年
如果這些年丟失,則沒有絕對的萬無一失的方法來處理這些年。當日期回到過去并在這種情況下添加 1 年時,我們可以做些什么來推斷年份變化:
# let's assume the starting year is 2017
date = pd.to_datetime(df.index.rename(['month', 'day']).to_frame().assign(year=2017))
df.index = date date.diff().lt('0').cumsum().mul(pd.DateOffset(years=1))
輸出:
A B C
2017-01-01 21 32 4
2017-01-02 4 2 23
2017-06-03 12 9 10
2017-06-04 1 56 37
2018-01-30 63 1 27 # added 1 year
2018-01-31 32 2 32
2018-12-01 2 3 23
2018-12-02 23 1 12
2018-12-03 32 3 23
2018-12-31 23 2 32
使用的輸入:
A B C
1 1 21 32 4
2 4 2 23
6 3 12 9 10
4 1 56 37
1 30 63 1 27 # here we go back from month 1 after month 6
31 32 2 32
12 1 2 3 23
2 23 1 12
3 32 3 23
31 23 2 32
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/531767.html
