1

I am trying to create a new column in my pandas Dataframe by passing multiple conditional statements through a lambda function.

My question is very similar to this one: Lambda including if...elif...else but the solution doesn't seem to work for my version of python (3.7).

Here's what I have so far:

With one condition, this works:

ops['repair_location'] = ops['depot_name'].apply(lambda x: 'Field' if x == 'Field else 'Depot')

But I want to add another condition. Using the solution to the linked question:

ops['repair_location'] = ops['depot_name'].apply(lambda x: 'Field' if x == 'Field' else (x == 'Unknown Location' 'Unknown Location' else 'Depot'))

This returns a syntax error pointing to the last else statement.

1
  • What were you intending with this expression: x == 'Unknown Location' 'Unknown Location'? In any case, you just have a bare-except, that isn't a complete conditional expression. You really should just use a full function definition, this lambda will quickly become unreadable Commented Apr 16, 2020 at 0:26

2 Answers 2

2

You can use np.where

import numpy as np
ops['repair_location'] = (
    ops['depot_name']
    .apply(lambda x: np.where(x=='Field', 'Field', np.where(x=='Unknown Location', 'Unknown Location', 'Depot')))
)
Sign up to request clarification or add additional context in comments.

2 Comments

May I know why we do apply here?
That's what the OP wanted to use and just trying to make it work.
2

We usually do np.select

s1=ops['depot_name']=='Field'
s2=ops['depot_name']=='Unknown Location'
ops['repair_location']=np.select([s1,s2],['Field','Unknown Location'],default='Depot')

2 Comments

The column depot_name has values outside of 'Field' and 'Unknown Location'. This rewrites it and returns an error ValueError: invalid entry 0 in condlist: should be boolean ndarray
@Jacky please try again typo '=='

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.