示例
import pandas as pd
idx = pd.Index(['2022-01-03 09:00:00'], name='timestamp')
df = pd.DataFrame([[12, 3, 31]], index=idx, columns=['data', 'day_of_month', 'days_in_month'])
df
data day_of_month days_in_month
timestamp
2022-01-03 09:00:00 12 3 31
代码
使用set_index
配合append
参数和swaplevel
方法:
out = df.set_index('days_in_month', append=True).swaplevel(0, 1)
out
data day_of_month
days_in_month timestamp
31 2022-01-03 09:00:00 12 3