Find differences in strings on pandas column

Viewed 41

I have the following pandas DataFrame from this CSV file

import pandas as pd
df=pd.read_csv('Last_year.csv')
df.groupby('School Status').size().plot(kind='pie', autopct='%1.1f%%') 

I would like to know how I can remove the error which is causing me to have 3 divisions and not 2 as programmed

Here is the result enter image description here

2 Answers

Seems like you're having these three dimensions in your DataFrame.

df['School Status'].unique()

array(['IN SCHOOL', 'OUT OF SCHOOL', 'OUT OF SCHOOL '], dtype=object)

So, if you'll remove whitespace after the last one, it should work properly:

Try this snippet:

import pandas as pd
df=pd.read_csv('Last_year.csv')
df['School Status'] = df['School Status'].replace({'OUT OF SCHOOL ': 'OUT OF SCHOOL'})
df.groupby('School Status').size().plot(kind='pie', autopct='%1.1f%%')

You may have more spaces in one of the labels.

To check what are the labels that pandas detects, you can use Series.unique().

You can remove whitespace from beginning and end for example by using str.strip element-wise, doing:

import pandas as pd  # This code is from OP
df=pd.read_csv('Last_year.csv')  # This code is from OP
df['School Status'] = df['School Status'].map(str.strip)
df.groupby('School Status').size().plot(kind='pie', autopct='%1.1f%%')  # This code is from OP
# Now you can plot your DF
Related