Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use apply function avoiding nans

Tags:

python

pandas

I have this function:

###############################################################################
def decdeg2dms(dd):
    is_positive = dd >= 0
    dd = abs(dd)
    minutes,seconds = divmod(dd*3600,60)
    degrees,minutes = divmod(minutes,60)
    degrees = degrees if is_positive else -degrees
    value=str(int(degrees))+'°'+str(int(minutes))+'\''+str(round(seconds,2))+'\"'
    return value
###############################################################################

I want to apply decdeg2dms fuction to some columns in a df so i wrote this code:

#Initial values of Latitude and Longitude in string
    df['LATITUDE']=df['LATITUDE'].astype(float).apply(decdeg2dms)
    df['LONGITUDE']=df['LONGITUDE'].astype(float).apply(decdeg2dms)

But i get this error:

ValueError: cannot convert float NaN to integer

I don't want to remove nan values, just apply the function in the non NaN values so i tried this:

df[['LATITUDE','LONGITUDE']].apply(lambda x: decdeg2dms(x) if(np.all(pd.notnull(x))) else x, axis = 1)

But i get this error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

How can i just apply the function in the non NaN values without removing nan values?

like image 238
Javier Avatar asked Sep 14 '25 09:09

Javier


1 Answers

The first option:

def decdeg2dms(dd):
    if pd.isnull(dd):
        return None
    ...

df['LATITUDE']=df['LATITUDE'].astype(float).apply(decdeg2dms)

The second option

df['LATITUDE']=df['LATITUDE'].astype(float).apply(lambda x: decdeg2dms(x) if pd.notnull(x) else x)
like image 200
Alexander Volkovsky Avatar answered Sep 17 '25 00:09

Alexander Volkovsky