【问题标题】:How to manually arrange index of Value_counts in Python如何在 Python 中手动排列 Value_counts 的索引
【发布时间】:2020-10-22 15:51:13
【问题描述】:

我想根据我的数据中月份的值计数得到一个条形图。当我绘制图表时,我按值的降序排列。但我希望图表根据月份,即一月的第一个条形图,二月的第二个条形图,依此类推。

代码

months = df_Badge.Date.dt.month_name().value_counts()
sns.barplot(months.index, months.values, alpha=0.8)

【问题讨论】:

    标签: python-3.x pandas matplotlib group-by seaborn


    【解决方案1】:

    首先,如果可能缺少某些月份,则可以使用 ordered categoricals 与月份列表中的所有类别:

    months = ['January','February','March','April',
              'May','June','July','August',
              'September','October','November','December']
    
    
    months = df_Badge.Date.dt.month_name().value_counts()
    
    months.index = pd.CategoricalIndex(months.index, ordered=True, categories=months)
    months = months.sort_index()
    
    sns.barplot(months.index, months.values, alpha=0.8)
    

    如果索引中的所有月份都可能使用Series.reindex,如果缺少某个月份,则添加缺失值:

    months = ['January','February','March','April',
              'May','June','July','August',
              'September','October','November','December']
    
    months = df_Badge.Date.dt.month_name().value_counts().reindex(months)
    sns.barplot(months.index, months.values, alpha=0.8)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多