【问题标题】:Include zeros in count_values pandas categorial data在 count_values pandas 分类数据中包含零
【发布时间】:2019-12-24 17:38:10
【问题描述】:

这是我之前提出的问题的后续问题。老问题可以找到here,我收到了@jezrael发来的answer

现在我想绘制成绩。

为了绘制我能做的所有成绩

counts_gardes = df1['new'].value_counts(sort=False)
counts_gardes.plot(kind='bar')

但是,我不知道如何绘制每个年级组,包括零计数。

counts_gardes_group = df1['new'].value_counts(sort=False)
counts_gardes_group.plot(kind='bar')

我还想在绘制的数字中包括 F 的零计数。我尝试了hereherehere 中提供的解决方案,但没有奏效。第一个返回所有成绩,而后者给出一个错误,指出index 没有levels

非常感谢任何帮助。

【问题讨论】:

  • 那么问题是如果没有Fs,那么这些就不能算了。 Pandas 根本不知道存在类似 F 的东西。

标签: python pandas


【解决方案1】:

您可以将Series.reindex 与所有等级列表的交换顺序(如有必要)一起使用,如果不匹配则替换为0

grade_leters = ['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D','D-', 'F']

counts_gardes_group = (df1['new'].value_counts(sort=False)
                                 .reindex(grade_leters[::-1], fill_value=0))
counts_gardes_group.plot(kind='bar')

【讨论】:

    【解决方案2】:

    这对我有用。

    new_index = sorted(set([x[0] for x in df1['new'].cat.categories]), reverse=True)
    counts_gardes_group = df1['new'].str[0].value_counts(sort=False).reindex(
         new_index, fill_value=0
    )
    
    counts_gardes_group.plot(kind='bar')
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-02
      • 1970-01-01
      • 2019-03-17
      • 1970-01-01
      • 2021-02-04
      • 2014-02-05
      • 2012-03-19
      相关资源
      最近更新 更多