Home > Software design >  Skipping empty values python apply
Skipping empty values python apply

Time:02-23

I need to apply the right function to a column ('Example') in a dataframe. The following code works perfectly if the column has no empty "cells". However, when it comes to columns with some empty cells I get "TypeError: 'float' object is not subscriptable".

def right(x):
    return x[-70:]
df1['Example'] = df1['Example'].apply(right)

For empty "cells" I would actually need to keep them empty. Any help much appreciated!

CodePudding user response:

You need an if else, apply your function only if x is of type(int)

CodePudding user response:

It's better if you use a boolean mask to avoid a condition statement in your function:

m = df1['Example'].notna()
df1.loc[m, 'Example'] = df1.loc[m, 'Example'].apply(right)

CodePudding user response:

I'd modify your function to skip the floats (which are actually NaNs):

def right(x):
    if np.isnan(x):
        return np.nan
    return x[-70:]
  • Related