简体   繁体   English

用熊猫作图:分组和均值

[英]Plot with pandas: group and mean

My data from my 'combos' data frame looks like this: 我来自“ combos”数据框的数据如下所示:

pr = [1.0,2.0,3.0,4.0,1.0,2.0,3.0,4.0,1.0,2.0,3.0,4.0,.....1.0,2.0,3.0,4.0]

lmi = [200, 200, 200, 250, 250,.....780, 780, 780, 800, 800, 800]

pred = [0.16, 0.18, 0.25, 0.43, 0.54......., 0.20, 0.34, 0.45, 0.66]

I plot the results like this: 我绘制这样的结果:

fig,ax = plt.subplots()

for pr in [1.0,2.0,3.0,4.0]:
    ax.plot(combos[combos.pr==pr].lmi, combos[combos.pr==pr].pred, label=pr)

ax.set_xlabel('lmi')
ax.set_ylabel('pred')
ax.legend(loc='best')

And I get this plot: 我得到这个情节:

在此处输入图片说明

How can I plot means of "pred" for each "lmi" data point when keeping the pairs (lmi, pr) intact? 保持对(lmi,pr)对完整时,如何绘制每个“ lmi”数据点的“ pred”平均值?

As of your updates to the question it is now clear that you want to calculate the means for each pair (pr, lmi) . 在更新问题时,现在很清楚,您要计算每对(pr, lmi)的均值。 This can be done by grouping over these columns and then simply calling mean() . 这可以通过对这些列进行分组,然后简单地调用mean() With reset_index() , we then restore the DataFrame format to the previous form. 使用reset_index() ,然后将DataFrame格式恢复为以前的形式。

$ combos.groupby(['lmi', 'pr']).mean().reset_index()

   lmi   pr  pred
0  200  1.0  0.16
1  200  2.0  0.18
2  200  3.0  0.25
3  250  1.0  0.54
4  250  4.0  0.43
5  780  2.0  0.20
6  780  3.0  0.34
7  780  4.0  0.45
8  800  1.0  0.66

In this new DataFrame pred does contain the means and you can use the same plotting procedure you have been using before. 在这个新的DataFrame中, pred确实包含了方法,您可以使用以前使用过的相同绘制过程。

You can first group your DataFrame by lmi then compute the mean for each group just as your title suggests: 您可以先DataFrame lmiDataFrame ,然后按照标题所示计算每组的平均值:

combos.groupby('lmi').pred.mean().plot()

In one line we: 在一行中,我们:

  1. Group the combos DataFrame by the lmi column lmi列对组合DataFrame进行分组
  2. Get the pred column for each lmi 获取每个lmipred
  3. Compute the mean across the pred column for each lmi group 计算每个lmi组在pred列上的平均值
  4. Plot the mean for each lmi group 绘制每个lmi组的均值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM