简体   繁体   English

如何防止 pd.pivot_table 对列进行排序

[英]How prevent pd.pivot_table from sorting columns

I have the following long df:我有以下长df:

df = pd.DataFrame({'stations':["Toronto","Toronto","Toronto","New York","New York","New York"],'forecast_date':["Jul 30","Jul 31","Aug 1","Jul 30","Jul 31","Aug 1"],'low':[58,57,59,70,72,71],'high':[65,66,64,88,87,86]})
print(df)

I want to pivot the table to a wide df that looks like this:我想将表格旋转到一个宽 df,如下所示:

Desired Output期望的输出

so I used the following function:所以我使用了以下功能:

df = df.pivot_table(index = 'stations', columns = "forecast_date", values = ["high","low"],aggfunc = "first").reset_index()
print(df)

but with this, I get the following df:但有了这个,我得到以下df:

Output Received (Undesired)接收到的输出(不需要)

So basically pd.pivot_table seems to be sorting the columns alphabetically, whereas I want it to be sorted in chronological order所以基本上 pd.pivot_table 似乎是按字母顺序对列进行排序,而我希望它按时间顺序排序

Any help would be appreciated,任何帮助,将不胜感激,

( Note that the dates are continuously changing, so other months will have a similar problem ) 注意日期是不断变化的,所以其他月份也会有类似的问题

You won't be able to prevent the sorting, but you can always enforce the original ordering by using .reindex with the unique values from the column!您将无法阻止排序,但您始终可以通过将.reindex与列中的唯一值一起使用来强制执行原始排序!

table = df.pivot_table(index = 'stations', columns = "forecast_date", values = ["high","low"],aggfunc = "first")

print(
    table
)
               high                 low              
forecast_date Aug 1 Jul 30 Jul 31 Aug 1 Jul 30 Jul 31
stations                                             
New York         86     88     87    71     70     72
Toronto          64     65     66    59     58     57


print(
    table.reindex(columns=df['forecast_date'].unique(), level='forecast_date')
)
                high                 low             
forecast_date Jul 30 Jul 31 Aug 1 Jul 30 Jul 31 Aug 1
stations                                             
New York          88     87    86     70     72    71
Toronto           65     66    64     58     57    59

Note that this is different than sorting in chronological order.请注意,这与按时间顺序排序不同。 To do that you would have to cast to a datetime and sort on that.为此,您必须转换为datetime时间并对其进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM