如何在不打乱索引顺序的情况下格式化 pandas 数据框索引列上的日期?

问题描述 投票:0回答:1

我在格式化数据帧索引而不打乱其顺序时遇到问题。 给定数据框:

Reference_Date  2023    2024    2025    2026    2027    2028
Data_Date                       
2023-01-02  12.2500 9.0000  8.0000  8.0000  8.0000  NaN
2023-01-03  12.2500 9.0000  8.0000  8.0000  8.0000  NaN
2023-01-04  12.2500 9.0000  8.0000  8.0000  8.0000  NaN
2023-01-05  12.2500 9.0000  8.0000  8.0000  8.0000  NaN
2023-01-06  12.2500 9.2500  8.0000  8.0000  8.0000  NaN
... ... ... ... ... ... ...
2024-03-22  NaN 9.0000  8.5000  8.5000  8.5000  8.2500
2024-03-25  NaN 9.0000  8.5000  8.5000  8.5000  8.2500
2024-03-26  NaN 9.0000  8.5000  8.5000  8.5000  8.250

请记住,我做了:

df_pivot = df.pivot_table(index='Data', columns='Reference_Date', values='Value')
,结果如上表所示。

我正在尝试将 Data_Date 从 '%Y-%m-%d' 格式化为 '%d/%m/%Y'。

我在旋转桌子之前尝试过:

df['Data_Date'] = pd.to_datetime(df['Data_Date'], format='%Y-%m-%d') 
df['Data_Date']= df['Data_Date'].dt.strftime('%d/%m/%Y')

它按照我想要的方式格式化,但顺序混乱了:

DataReferencia  2023    2024    2025    2026    2027    2028
Data                        
01/02/2023  12.5000 9.5000  8.7500  8.5000  8.5000  NaN
01/02/2024  NaN 9.0000  8.5000  8.5000  8.5000  8.5000
01/03/2023  12.7500 10.0000 9.0000  8.5000  8.5000  NaN
01/03/2024  NaN 9.0000  8.5000  8.5000  8.5000  8.5000
01/06/2023  12.5000 10.0000 9.0000  9.0000  9.0000  NaN
... ... ... ... ... ... ...
31/03/2023  12.7500 10.0000 9.0000  8.7500  9.0000  NaN
31/05/2023  12.5000 10.0000 9.0000  9.0000  9.0000  NaN
31/07/2023  12.0000 9.2500  8.7500  8.5000  8.7500  NaN

我该怎么办?有没有办法做到这一点?抱歉我的英语不好。

python pandas sorting formatdatetime
1个回答
0
投票

按索引进行枢轴排序后(

sort_index
功能)

out = df_pivot.sort_index(key=lambda x: pd.to_datetime(x))
© www.soinside.com 2019 - 2024. All rights reserved.