How do I find the mode of a column of categorical data?

Viewed 3603

I want to find the most repetitive value (which is the mode) of a column of categorical data and fill the blank cells with this value.

"Embarked" column has only three values: S,Q,C

When I try to calculate mean and median it gives an error already, because its no numerical value, but I can take a mode of this column, when I try this part of code it doesn't give an error:

embarked=df_missing['Embarked']
df_missing['Embarked']=df_missing['Embarked'].fillna(embarked.mode())

But it also doesn't fill the empty cells. How can I find the mode of this column.

1 Answers

That should be working, but try this approach.

First try df_missing['Embarked'].value_counts() and see whether you get what you expect.

Then try:

embarked_mode = df_missing['Embarked'].mode()
df_missing['Embarked'].fillna(embarked_mode, inplace=True)

If your columns doesn't contain cells aren't actually Na then as @Quang Hoang says, it may be that you have empty strings. In this case you can try:

embarked_mode = df_missing['Embarked'].mode()
df_missing['Embarked'].replace('\s+', embarked_mode, regex=True, inplace=True)
Related