[英]Python pandas: pivot table columns sorting
This is my sorted dataframe by year
and month
:这是我按year
和month
排序的 dataframe :
df:东风:
Year Month YearMonthName revenue
2015 1 2015 Jan 166
2015 2 2015 Feb 170
2015 3 2015 Mar 187
2015 4 2015 Apr 102
2015 5 2015 May 166
... ... ... ...
2020 12 2020 Dec 133
So the col
list is also sorted by year
and month
:所以col
列表也按year
和month
排序:
col=list(df['YearMonthName'])
print(col)
Result:结果:
[' 2015 Jan', ' 2015 Feb', ' 2015 Mar', ' 2015 Apr', ... , ' 2020 Dec']
But when I put the col
list into pandas pivot table, columns are sorted alphabetically by YearMonthName
.但是,当我将col
列表放入 pandas pivot 表中时,列按YearMonthName
的字母顺序排序。 Any ideas how can I sort this?任何想法我该如何排序?
df_table1 = pd.pivot_table(df, values='revenue', columns=col, aggfunc=np.sum).reset_index()
print(df_table1)
Result:结果:
index 2015 Apr ... 2020 Oct 2020 Sep
0 revenue 353726 ... 349309 340451
what you could do is first perform the pivoting then reindex by cols, as followed:您可以做的是首先执行旋转,然后按 cols 重新索引,如下所示:
# given that you have sorted YearMonthName
col = df['YearMonthName'].tolist()
# pivot table as you did
pv = df.pivot_table(values='revenue', columns='YearMonthName', aggfunc='sum')
then you can reindex using the variable col
:然后您可以使用变量col
重新索引:
pv = pv.reindex(labels=col, axis=1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.