1

I have the following command:

df1['parent'] = df1['x'].map(lambda x: x.split('by')[1])

and I get:

IndexError: list index out of range

For some of the values in the column,there is nothing after the "by", how I can do something like: if there is nothing after by then write ""

1 Answer 1

2

Use str.split with indexing with str which return NaN if no value, so then add fillna:

df1 = pd.DataFrame({'x':['ddbytrr','df']})
print (df1)
         x
0  ddbytrr
1       df

df1['parent'] = df1['x'].str.split('by').str[1].fillna('')
print (df1)
         x parent
0  ddbytrr    trr
1       df

Solution with map and if-else, but it only works if no NaNs values in column:

df1['parent'] = df1['x'].map(lambda x: x.split('by')[1] if len(x.split('by')) > 1 else '')
print (df1)
         x parent
0  ddbytrr    trr
1       df 

What is same as numpy.where solution:

splitted = df1['x'].str.split('by')
df1['parent'] = np.where(splitted.str.len() > 1, splitted.str[1], '')
print (df1)
         x parent
0  ddbytrr    trr
1       df    
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for the detailed answer

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.