1

I have the following pandas DataFrame df:

Datetime Field1 Field2 2018-10-01 10:00 10 13 2018-10-01 11:00 18 14 2018-10-01 12:00 11 16 2018-10-01 13:00 12 15 2018-10-01 14:00 13 15 2018-10-01 15:00 11 11 2018-10-02 10:00 14 15 2018-10-02 11:00 15 15 2018-10-02 12:00 12 12 2018-10-02 13:00 11 15 2018-10-02 14:00 10 13 2018-10-02 15:00 10 15 2018-10-03 10:00 15 11 2018-10-03 11:00 13 12 2018-10-03 12:00 11 12 2018-10-03 13:00 11 11 2018-10-03 14:00 11 13 2018-10-03 15:00 12 15 

I need to create a box plot to show how the values of Field2 are distributed when grouped by Field1. The result should be conceptually similar to this plot, where X should be Field1 and Y should be Field2):

enter image description here

This is what I tried:

df = df.set_index("Field1") grouped = df.groupby(level="Field1") grouped.boxplot(rot=45, fontsize=12, figsize=(10,5)) 

But this code gets stuck and does not provide any results.

3
  • 1
    Are you using the latest pandas and matplotlib versions? Commented May 31, 2021 at 13:52
  • 1
    If you're fine using seaborn you can do: sns.boxplot(data=df, x="Field1", y="Field2") Commented May 31, 2021 at 13:55
  • The easiest way to create such a plot is via seaborn's sns.boxplot(data=df, x='Field1', y='Field2') on the original dataframe (without the set_index). Commented May 31, 2021 at 13:55

1 Answer 1

1

If I understand what you're asking you should reshape your dataframe then plot:

df_ = df.pivot(columns=["Field1"], values=["Field2"]) df_.columns = df_.columns.droplevel(0) df_.boxplot(rot=45, fontsize=12, figsize=(10,5)) 

Which outputs:

enter image description here


Alternatively, using seaborn, which requires no pivoting/grouping by you:

sns.boxplot(data=df, x="Field1", y="Field2") 

enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

I get KeyError: 'Level Field1 not found'
For which example?
For the 1st one.
It won't work if you've already set the index to Field1. That should be a Series, not the index.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.