我有一個數據框,其中索引是多重索引,如下所示; 1 2 3 4 52020 6 7 8 9 10 11 12由于我需要每日值,我希望將其轉換為如下列;Date2020/01/012020/02/012020/03/012020/04/012020/05/01etc 這樣我就可以使用;df.set_index('Date').resample('D').ffill()非常感謝任何幫助!
1 回答

至尊寶的傳說
TA貢獻1789條經驗 獲得超10個贊
如果索引中只有year并且month級別使用列表理解并更改連接字符串的格式:
#python 3
df.index = pd.to_datetime([f'{a}--01' for a, b in df.index])
#python 2
df.index = pd.to_datetime(['{}-{}-01'.format(a, b) for a, b in df.index])
如果還有天:
#python 3
df.index = pd.to_datetime([f'{a}--{c}' for a, b, c in df.index])
#python 2
df.index = pd.to_datetime(['{}-{}-{}'.format(a, b, c) for a, b, c in df.index])
進而:
df1 = df.resample('D').ffill()
添加回答
舉報
0/150
提交
取消