mardi 24 décembre 2019

Why Pandas "apply" function is introducing NULL values in newly added column?

I'm trying to add a new column to dataframe shown below:

     PM10  PM2.5   SO2    NO2     O3  
     4.0    4.0   4.0    7.0    77.0   
    24.0   24.0  26.0   54.0    36.0   
    19.0   15.0  21.0   57.0    32.0    
    35.0   26.0  22.0   54.0    43.0   
    40.0   37.0  24.0   55.0    44.0     
    79.0   54.0  50.0   80.0    24.0  
    120.0   93.0  87.0  107.0    2.0  

I'm trying to add a new column by using the "if-else" condition but when i tried to do that by using the following function:

def aqi(x):
if x in range(0,30):
    return "Good"
elif x in range(31,60):
    return "Satisfactory"
elif x in range(61,90):
    return "Moderately Polluted"
elif x in range(91,120):
    return "Poor"
elif x in range(121,250): 
    return "Very Poor"
elif x in range(250,1000):
    return "Severe"
return

df["aqi"] = df.PM10.apply(aqi)

The function is working and not throwing any error but its introducing null values in the new column (last row). As we can see there isn't any null value in column "PM10".

     PM10  PM2.5   SO2    NO2     O3      aqi
     4.0    4.0   4.0    7.0    77.0      Good
    24.0   24.0  26.0   54.0    36.0      Good
    19.0   15.0  21.0   57.0    32.0      Good
    35.0   26.0  22.0   54.0    43.0      Satisfactory
    40.0   37.0  24.0   55.0    44.0      Satisfactory
    79.0   54.0  50.0   80.0    24.0      Moderately Polluted
    120.0   93.0  87.0  107.0   2.0       None

It's a pretty trivial issue and still i haven't been able to figure it out.

Aucun commentaire:

Enregistrer un commentaire