pandas 带有熊猫和 groupby 的箱线图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29868091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 15:38:54  来源:igfitidea点击:

Boxplot with pandas and groupby

pandasmatplotlib

提问by nicholas.reichel

I have the following dataset sample:

我有以下数据集样本:

     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

And need a box and whisker plot, grouped by column 0. I have the following:

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

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

But I end up with three subplots. How can place all three on one plot? Thanks. enter image description here

但我最终得到了三个子图。如何将所有三个放在一个地块上?谢谢。 在此处输入图片说明

采纳答案by Alexander

I don't believe you need to use groupby.

我不相信你需要使用 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

箱形图

回答by fixxxer

In 0.16.0 version of pandas, you could simply do this:

在 0.16.0 版本的 pandas 中,您可以简单地执行以下操作:

df.boxplot(by='0')

Result:

结果:

enter image description here

在此处输入图片说明