10

Say I have a dataframe like the following:

my_dataframe:

   Age  Group
0  31   A
1  24   A
2  25   A
3  36   A
4  50   NaN
5  27   A
6  49   A
7  24   A
8  63   A
9  25   A
10  65  A
11  67  A
12  59  A
13 NaN  B
14  30  B
15  19  B
16  57  B
17  62  B
18  30  B
19  50  B
20  42  B
21  45  C
22  59  C
23  28  C
24  37  C
25  29  C

I would like to boxplot the age of each Group (A,B,C). Note that I have some NaN values in the dataframe. How can I do this in Pandas?

Amelio Vazquez-Reina
  • 91,494
  • 132
  • 359
  • 564

1 Answers1

17

Misread 1st time so gave answer for histograms... keeking that below. for boxplot the code is:

bp = df.boxplot(by='Group')

enter image description here

suptitle('Bla Bla')

to change or get rid of the automatically generated top Title.

Might be a more elegant way but the following works for histograms:

df[df.Group =='A'].Age.hist()
df[df.Group =='B'].Age.hist()
df[df.Group =='C'].Age.hist()

http://pandas.pydata.org/pandas-docs/dev/visualization.html has some fancy syntax to do this as well. But since only have 3 groups the simple solution is probably sufficient.

Joop
  • 7,840
  • 9
  • 43
  • 58
  • Thanks.. Do you know how to get rid of `"Boxplot grouped X"` in the figure title? – Amelio Vazquez-Reina Aug 01 '13 at 12:17
  • Don't have the example data open anymore... if in ipython with pylab imports: simply title("Boxplot grouped X") should do. Otherwise "import matplotlib.pylab as plt" and plt.title(".....") should do the trick – Joop Aug 01 '13 at 15:05
  • Thanks Joop, unfortunately the title command just changes the part that says `Age` in the boxplot (in your post), that's why I asked. – Amelio Vazquez-Reina Aug 01 '13 at 17:20
  • "Boxplot grouped by Group" is in space used by suptitle. but it merely over-writes stuff there so it stays messy. – Joop Aug 02 '13 at 06:52
  • My production pandas is still 0.10.0 Checked with 0.11.0 and suptitle is method to get to the other title. Seems to be a bug using 0.10.0 that overwrites the subtitle, but the with invisibe background so previous one still shows. – Joop Aug 02 '13 at 07:07