【问题标题】:Sorting correctly month in a plot在图中正确排序月份
【发布时间】:2022-01-17 17:02:07
【问题描述】:

我编写了一个代码(在 pyspark 中适用于数据框 pandas)来绘制历史系列图:以年为单位的数量趋势。在 x 轴上,我输入了月份的名称。我怎样才能正确地而不是按字母顺序排列它们?

谢谢

plt.figure()
pd_filter = df[df["date"] < pd.to_datetime("2021-12-01")].copy()
pd_new = pd.DataFrame(pd_filter.groupby(["Month","Year"])["quantity"].count()).reset_index()
ax = pd_new.set_index("Month").groupby("Year")["quantity"].plot(legend=True, figsize=(10,5), title = "Quantity per Year")
plt.xlabel("Months")
plt.ylabel("Quantity")
plt.show()

【问题讨论】:

    标签: python sorting pyspark


    【解决方案1】:

    你可以用字典map月份字符串月份数,然后用月份数作为索引,排序指数。下面是一个小例子:

    import pandas as pd
    
    df = pd.DataFrame(
        {"Month": ["Feb", "Jan", "Mar", "May", "Jun", "Jul", "Oct", "Apr", "Aug", "Sep", "Dec", "Nov"],
         "Val": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]})
    
    month_map = {"Jan": 1, "Feb": 2, "Mar": 3, "Apr": 4, "May": 5, "Jun": 6, "Jul": 7, "Aug": 8, "Sep": 9, "Oct": 10,
                 "Nov": 11, "Dec": 12}
    
    df["Month_val"] = df["Month"].map(month_map)
    df_new_index = df.set_index("Month_val").sort_index()
    df_new_index.plot.line(x="Month", y="Val")
    

    您可能需要将字典中的字符串更改为您在月份中使用的字符串。

    输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多