在count_values大熊猫分类数据中包含零

时间:2019-12-24 08:17:01

标签: python pandas

这是我先前提出的问题的后续问题。可以找到旧问题here,我收到了answer@jezrael

现在我要绘制成绩。

要绘制所有我能做的成绩

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

enter image description here

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

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

enter image description here

我还要在图中绘制F的零计数。我尝试了hereherehere中提供的解决方案,但是它们没有用。前者返回所有成绩,而后者给出错误,指出index没有levels

我们非常感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

您可以将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')

答案 1 :(得分:0)

这对我有用。

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