Pandas:生成和绘制平均值

2024-05-16 20:02:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个熊猫数据框,比如:

In [61]: df = DataFrame(np.random.rand(3,4), index=['art','mcf','mesa'],
                        columns=['pol1','pol2','pol3','pol4'])

In [62]: df
Out[62]: 
          pol1      pol2      pol3      pol4
art   0.661592  0.479202  0.700451  0.345085
mcf   0.235517  0.665981  0.778774  0.610344
mesa  0.838396  0.035648  0.424047  0.866920

我想生成一行基准上的策略平均值,然后绘制出来。

目前,我的做法是:

df = df.T
df['average'] = df.apply(average, axis=1)
df = df.T
df.plot(kind='bar')

有没有一个优雅的方法来避免双重换位?

我试过:

df.append(DataFrame(df.apply(average)).T)
df.plot(kind='bar')

这将追加正确的值,但不会正确更新索引,并且图形会出现混乱。

一个澄清。带有双转置的代码的结果是:enter image description here 这就是我想要的。显示政策的基准和平均值,而不仅仅是平均值。我只是好奇我能不能做得更好。

请注意,传说通常是混乱的。为了解决这个问题:

ax = df.plot(kind='bar')
ax.legend(patches, list(df.columns), loc='best')

Tags: columnsindataframedfplotbar平均值average
1条回答
网友
1楼 · 发布于 2024-05-16 20:02:53

您可以简单地使用DataFrame的实例方法mean,然后绘制结果。不需要换位。

In [14]: df.mean()
Out[14]: 
pol1    0.578502
pol2    0.393610
pol3    0.634424
pol4    0.607450

In [15]: df.mean().plot(kind='bar')
Out[15]: <matplotlib.axes.AxesSubplot at 0x4a327d0>

policies.png

更新

如果要绘制所有列的条形图和平均值,可以append平均值:

In [95]: average = df.mean()

In [96]: average.name = 'average'

In [97]: df = df.append(average)

In [98]: df
Out[98]: 
             pol1      pol2      pol3      pol4
art      0.661592  0.479202  0.700451  0.345085
mcf      0.235517  0.665981  0.778774  0.610344
mesa     0.838396  0.035648  0.424047  0.866920
average  0.578502  0.393610  0.634424  0.607450

In [99]: df.plot(kind='bar')
Out[99]: <matplotlib.axes.AxesSubplot at 0x52f4390>

second plot

如果布局不适合子批次^{}将调整matplotlib参数。

相关问题 更多 >