使用 pd.crosstab 按日期降序排序

Sort By Dates Descending Using pd.crosstab

我正在尝试从 NYC COVID 网站下载数据,做一些清理,然后做一个交叉表,以日期为列,以区域为行。

问题是我做交叉表的时候。日期从左到右按升序显示,我希望在左侧看到最近的日期,然后随着列向右移动而变旧。

非常感谢您的帮助 - 这让我很困惑。谢谢!

所以我的 headers 目前看起来像:|

week_ending 2020-08-08 2020-08-15

我需要它们看起来像:|

week_ending 2021-02-13 2021-02-06

代码如下

import pandas as pd

trendszipcode='https://raw.githubusercontent.com/nychealth/coronavirus-data/master/trends/percentpositive-by-modzcta.csv'


trendszipcode = pd.read_csv(trendszipcode,delimiter=",", index_col="week_ending").reset_index()

df=pd.melt(trendszipcode, id_vars=['week_ending'])
df[['Toss','Region']] = df['variable'].str.split('_',expand=True)
df[['Region','week_ending','value']]
df.week_ending=pd.to_datetime(df.week_ending)
df_historical=df[['Region','week_ending','value']]
df_historical=df_historical.sort_values(by='week_ending', ascending=False)
pd.crosstab(df_historical.Region, df_historical.week_ending, values=df_historical.value, aggfunc='sum').round(2)

您可以将 DataFrame.sort_indexascending=Falseaxis=1 一起用于降序排列 DatetimeIndex:

的列
(pd.crosstab(df_historical.Region,df_historical.week_ending,values=df_historical.value,aggfunc='sum')
   .round(2)
   .sort_index(axis=1, ascending=False))