0

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 ''))

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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('')

2 Comments

this would not work for my situation as not all road names start with NSEW, but any road name could contain those letters
@InfinityCliff you mean the second approach? The first one should give the exact same result as the other answer, just avoiding to compute the split twice unnecessarily ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.