Search code examples
pythonpandasdataframefillna

Pandas fillna with string values from 2 other columns


I have a df with 3 columns, City, State, and MSA. Some of the MSA values are NaN. I would like to fill the MSA NaN values with a concatenation of City and State. I can fill MSA with City using df.MSA_CBSA.fillna(df.City, inplace=True), but some cities in different states have the same name.

City State MSA
Chicago IL Chicago MSA
Belleville IL Nan
Belleville KS Nan
City State MSA
Chicago IL Chicago MSA
Belleville IL Belleville IL
Belleville KS Belleville KS

Solution

  • Keep using the vectorized operation that you suggested. Notice that the argument can receive a combination from the other instances:

    df.MSA.fillna(df.City + "," + df.State, inplace=True)