【问题标题】:pandas: generate and plot averagepandas:生成并绘制平均值
【发布时间】:2012-12-15 08:35:45
【问题描述】:

我有一个 pandas 数据框,例如:

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

这将附加正确的值,但不会正确更新索引并且图表会混乱。

澄清。双转置的代码结果是这样的: 这就是我要的。显示政策的基准和平均值,而不仅仅是平均值。我只是好奇我能不能做得更好。

请注意,图例通常是混乱的。修复:

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

【问题讨论】:

  • 为什么您的数据采用这种结构?当您的列有数字并且您的行有名称时,总是有点可疑。将表格保持为转置格式似乎更有意义。然后,如果你想以另一种方式绘制它,你可以做d.T.plot()
  • 嗯,在计算机体系结构中,这种类型的图可能是所有研究论文的 99%。条形的高度代表原始 ipc(每个周期的指令)或标准化性能。
  • 当然,但我只是指出,如果它更有意义,您可以将数据存储为转置形式,并且仅 plot 以其他方向(通过绘制df.T 而不是 df)。

标签: python matplotlib plot pandas


【解决方案1】:

您可以简单地使用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>

更新

如果要绘制所有列的条形图和均值,可以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>

如果您的布局不适合子图 tight_layout 将调整 matplotlib 参数。

【讨论】:

  • 优秀。正是我想要的。另外,tight_layout 提示是一个要记住的提示,对此一无所知。
猜你喜欢
  • 2017-11-27
  • 1970-01-01
  • 2018-09-04
  • 1970-01-01
  • 2020-11-09
  • 1970-01-01
  • 2021-01-17
  • 1970-01-01
  • 2018-12-23
相关资源
最近更新 更多