Reputation: 45
In relation with this Group by Certain Age Group in Pandas
I am trying to group them in a single boxplot like this.
But I encountered an issue while using this code.
cn = ['AgeUnder18', 'Age19to25', 'Age26to29']
sns.boxplot(x=cn, y='AveMonthSpend', data=df)
Error:
The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Upvotes: 0
Views: 482
Reputation: 80279
You need to convert the dataframe to "long form":
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
cn = ['AgeUnder18', 'Age19to25', 'Age26to29']
df = pd.DataFrame({age_group: np.random.uniform(45, 65, 7) for age_group in cn})
df_melted = df.melt(value_vars=cn, value_name='AveMonthSpend', var_name='Age Bin')
sns.boxplot(y='Age Bin', x='AveMonthSpend', data=df_melted, palette='Greys')
plt.tight_layout()
plt.show()
This supposes the original dataframe looks like:
Out[10]:
AgeUnder18 Age19to25 Age26to29
0 64.980248 64.673755 56.489776
1 59.858895 48.921889 62.877826
2 62.357871 51.599347 55.651448
3 47.206124 45.817266 52.893839
4 57.627501 51.820863 59.616511
5 61.999523 63.443241 45.919390
6 56.616062 48.353018 46.282314
Upvotes: 1