Javier
Javier

Reputation: 513

Use apply function avoiding nans

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?

Upvotes: 4

Views: 4689

Answers (2)

ibadia
ibadia

Reputation: 919

df['LATITUDE']=df['LATITUDE'].apply(lambda x: decdeg2dms(x) if str(x)!='nan' else x)
df['LONGITUDE']=df['LONGITUDE'].apply(lambda x: decdeg2dms(x) if str(x)!='nan' else x)

In lambda function it means that the function that you defined will be applied on all of the values in the column LATITUDE AND LONGITUDE. I have set the if else condition for calling the function itself.

df['col']=df['col'].apply(lambda x: x if condition1 else condition 2) 

Upvotes: 1

Alexander Volkovsky
Alexander Volkovsky

Reputation: 2918

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)

Upvotes: 5

Related Questions