Home > Mobile >  Assign the value of another column to the empty cells of a specific column
Assign the value of another column to the empty cells of a specific column

Time:07-13

I have the following DataFrame in pandas:

code city district
01 London Westminster
03 Madrid NaN
04 Rome Trevi
07 Berlin NaN
08 Barcelona Badalona

For the district column if the row value is nan, I want to assign it the same value it has in its city attribute. Example:

code city district
01 London Westminster
03 Madrid Madrid
04 Rome Trevi
07 Berlin Berlin
08 Barcelona Badalona

CodePudding user response:

You should be able to use fillna() and pass the other column name:

df['district'] = df['district'].fillna(df['city'])

If the value is not Null (which I suggest to have it Null for best practices) but an empty string, you can evaluate a condition, so that:

df['district'] = np.where(df['district'] == '',df['city'],df['district'])
  • Related