如何停止在 pandas pivot table 中按字母顺序排列月份

How to stop months being ordered alphabetically in pandas pivot table

alphabetically-ordered months

如何停止 pandas 将 csv 中按时间顺序排列的数据转换为按字母顺序排列的数据(就像我当前的绘图)。这是我使用的代码:

import seaborn as sns

df = pd.read_csv("C:/Users/Paul/Desktop/calendar.csv")

df2 = df.pivot("Month", "Year", "hPM2.5")

ax = sns.heatmap(df2, annot=True, fmt="d")

我想你可以使用 ordered categorical:

import pandas as pd
import seaborn as sns

df = pd.DataFrame({'Month':['January','February','September'],
                   'Year':[2015,2015,2016],
                   'hPM2.5':[7,8,9]})

print (df)
       Month  Year  hPM2.5
0    January  2015       7
1   February  2015       8
2  September  2016       9


cats = ['January','February','March','April','May','June',
        'July','August','September','October','November','December']
df['Month'] = df['Month'].astype('category', 
                                  ordered=True,
                                  categories=cats)

df2 = df.pivot("Month", "Year", "hPM2.5")
sns.heatmap(df2, annot=True)