与熊猫和groupby的Boxplot

时间:2015-04-25 16:57:20

标签: pandas matplotlib

我有以下数据集示例:

     0         1
0    0  0.040158
1    2  0.500642
2    0  0.005694
3    1  0.065052
4    0  0.034789
5    2  0.128495
6    1  0.088816
7    1  0.056725
8    0 -0.000193
9    2 -0.070252
10   2  0.138282
11   2  0.054638
12   2  0.039994
13   2  0.060659
14   0  0.038562

需要一个盒子和胡须图,按第0列分组。我有以下内容:

plt.figure()
grouped = df.groupby(0)
grouped.boxplot(column=1)
plt.savefig('plot.png')

但我最终得到了三个子图。如何将所有三个放在一个地块上? 谢谢。 enter image description here

2 个答案:

答案 0 :(得分:25)

在0.16.0版本的熊猫中,你可以这样做:

df.boxplot(by='0')

结果:

enter image description here

答案 1 :(得分:9)

我认为你不需要使用groupby。

df2 = df.pivot(columns=df.columns[0], index=df.index)
df2.columns = df2.columns.droplevel()

>>> df2
0          0         1         2
0   0.040158       NaN       NaN
1        NaN       NaN  0.500642
2   0.005694       NaN       NaN
3        NaN  0.065052       NaN
4   0.034789       NaN       NaN
5        NaN       NaN  0.128495
6        NaN  0.088816       NaN
7        NaN  0.056725       NaN
8  -0.000193       NaN       NaN
9        NaN       NaN -0.070252
10       NaN       NaN  0.138282
11       NaN       NaN  0.054638
12       NaN       NaN  0.039994
13       NaN       NaN  0.060659
14  0.038562       NaN       NaN

df2.boxplot()

boxplot

相关问题