Home > Enterprise >  Use apply lambda with if else conditional without computing the condition twice
Use apply lambda with if else conditional without computing the condition twice

Time:04-20

Is there a way to apply the lambda statement without having to compute the x.split(' ')[0] twice? I know it can be done using a function i.e. .apply(lambda x: pre_dir(x) and take care of the logic there, but wondering if it can be done in a one-liner.

address.insert(6, 'PRE_DIR', address['STREETNAME'].apply(lambda x: x.split(' ')[0] if x.split(' ')[0] in ['N', 'S', 'E', 'W'] else ''))

CodePudding user response:

You could use where instead of apply. In other words, replace

address['STREETNAME'].apply(lambda x: x.split(' ')[0] if x.split(' ')[0] in ['N', 'S', 'E', 'W'] else '')

by

address['STREETNAME'].str.split(' ').str[0].where(lambda x: x.isin(['N', 'S', 'E', 'W']), '')

Example: For the following DataFrame

address = pd.DataFrame({'STREETNAME':['North Ave', '1st St', 'W 34th St']})

the above code produces the following column:

    0     
    1     
    2    W

CodePudding user response:

with python ≥ 3.8 you can use a assignment expression:

lambda x: y if (y:=x.split(' ')[0]) in ['N', 'S', 'E', 'W'] else '')

That said, IIUC, you could use a regex here:

address['STREETNAME'].str.extract('^([NSEW]) ').fillna('')
  • Related