[英]Sort By Dates Descending Using pd.crosstab
I am trying to download data from the NYC COVID website, do some cleaning, and then do a crosstab with dates as columns and the region as rows.我正在尝试从 NYC COVID 网站下载数据,进行一些清理,然后进行交叉表,其中日期为列,区域为行。
The problem is that when I do the crosstab.问题是当我做交叉表时。 the dates are presented in ascending order from left to right where I would like to see the most recent date on the left and then get older as the columns move to the right.日期从左到右按升序显示,我希望在左边看到最近的日期,然后随着列向右移动而变老。
I'd really appreciate some help - this has me stumped.我真的很感激一些帮助 - 这让我很难过。 Thanks!谢谢!
So my headers currently look like:|所以我的标题目前看起来像:|
week_ending周末结束 | 2020-08-08 2020-08-08 | 2020-08-15 2020-08-15 |
---|
And I need them to look like:|我需要它们看起来像:|
week_ending周末结束 | 2021-02-13 2021-02-13 | 2021-02-06 2021-02-06 |
---|
The code follows代码如下
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)
You can use DataFrame.sort_index
with ascending=False
and axis=1
for descending sorting columns fileld by DatetimeIndex
:您可以使用DataFrame.sort_index
和ascending=False
和axis=1
用于按DatetimeIndex
的降序排序列 fileld :
(pd.crosstab(df_historical.Region,df_historical.week_ending,values=df_historical.value,aggfunc='sum')
.round(2)
.sort_index(axis=1, ascending=False))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.