Dogukan Yılmaz
Dogukan Yılmaz

Reputation: 556

how to use if else with python pandas

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 ""

Upvotes: 1

Views: 252

Answers (1)

jezrael
jezrael

Reputation: 863741

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    

Upvotes: 2

Related Questions