Reputation: 135
titanic_df['Embarked'] = titanic_df['Embarked'].fillna("S")
titanic_df is data frame,Embarked is a column name. I have to missing cells in my column i.e blank spaces and I want to add "S" at the missing place but the code I mentioned above is not working.Please help me.
Upvotes: 1
Views: 2859
Reputation: 862641
I think you need replace
:
titanic_df['Embarked'] = titanic_df['Embarked'].replace(" ", "S")
Sample:
import pandas as pd
titanic_df = pd.DataFrame({'Embarked':['a','d',' ']})
print (titanic_df)
Embarked
0 a
1 d
2
titanic_df['Embarked'] = titanic_df['Embarked'].replace(" ", "S")
print (titanic_df)
Embarked
0 a
1 d
2 S
Also you can use str.replace
with regex if need replace one or more whitespaces.
^
means the beginning of whitespace(s), $
means the end of whitespace(s):
titanic_df = pd.DataFrame({'Embarked':['a ',' d',' ', ' ']})
print (titanic_df)
Embarked
0 a
1 d
2
3
titanic_df['Embarked'] = titanic_df['Embarked'].str.replace("^\s+$", "S")
#same output
#titanic_df['Embarked'] = titanic_df['Embarked'].replace("^\s+$", "S", regex=True)
print (titanic_df)
Embarked
0 a
1 d
2 S
3 S
Upvotes: 4
Reputation: 4864
Or you could use apply
titanic_df['Embarked'] = titanic_df['Embarked'].apply(lambda x: "S" if x == " " else x)
Upvotes: 1