Home > Blockchain >  Filling a missing value in a pandas data frame with an if statement based on a condition
Filling a missing value in a pandas data frame with an if statement based on a condition

Time:05-17

I have this Pandas data in which some values are missing. For example, in row 542 the value of LATITUDE is missing. My goal is based on the condition CNTY_CITY_LOC to fill the missing value of LATITUDE by applying if elif and apply function in Pandas. After I apply the if statement with the apply function of Pandas, the missing value is replaced but all other values in the LATITUDE column are missing. What am I doing wrong? Thanks for your help

Missing values in column LATITUDE row 542

IF statement apply function

Missing values in column Latitude

CodePudding user response:

First is necessary return value if no match, here NaN and for repalce only missing values in CA_LOCATION['LATITUDE'] use Series.fillna:

def CA_LATITUDE(county_CODE):
    if county_CODE == 4710:
       return 41.5188
    else:
       return np.nan

CA_LOCATION['LATITUDE'] = CA_LOCATION['LATITUDE'].fillna(CA_LOCATION.CNTY_CITY_LOC.apply(CA_LATITUDE))

Better is use Series.fillna with mapping by dictionary:

d= {4710:41.5188, 4711:41.5288...}
CA_LOCATION['LATITUDE'] = CA_LOCATION['LATITUDE'].fillna(CA_LOCATION.CNTY_CITY_LOC.map(d))
  • Related