我使用以下代码来绘制条形图:
df.groupby(['Borrow_Rank'])['Outcome'].mean().plot(kind = 'bar')
这显示了结果变量的平均值,范围为 0-1。但是,我还需要条形图来显示每个组中有多少个实例或行(每个组中有 2000-5000 个)。
最佳答案
您希望如何显示数据尚不清楚,但您可以使用多个聚合函数:
df.groupby(['Borrow_Rank'])['Outcome'].agg(['mean', 'count']).plot.bar()
输出:
其他选项,将计数注释为文本:
g = df.groupby(['Borrow_Rank'])['Outcome']
s = g.mean()
ax = s.plot.bar()
for x, (y, count) in enumerate(zip(s, g.count())):
ax.annotate(f'n = {count}', (x, y), ha='center', va='bottom')
输出:
可重现的虚拟输入:
df = pd.DataFrame({'Borrow_Rank': list('AABABACC'), 'Outcome': range(8)})
关于python - 按组绘制变量平均值,每个条形中具有指定数量的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72716278/