【问题标题】:How to stop months being ordered alphabetically in pandas pivot table如何停止在熊猫数据透视表中按字母顺序排列月份
【发布时间】:2017-04-23 19:22:44
【问题描述】:

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")

【问题讨论】:

  • 设为日期时间?

标签: python-3.x pandas matplotlib seaborn


【解决方案1】:

我想你可以使用有序的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)

【讨论】:

  • 谢谢,这对我来说是一个解决问题的方法。
猜你喜欢
  • 2021-02-03
  • 2021-01-06
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多