Create a column with ELIF in Pandas

Question

I find it difficult to understand how to create a new DataFrame column based on the values ​​in the other two columns. I need to use if / elif / else logic. But all the documentation and examples I found show only if / else logic. Here is an example of what I'm trying to do:

code

df['combo'] = 'mobile' if (df['mobile'] == 'mobile') elif (df['tablet'] =='tablet') 'tablet' else 'other') 

I am open to using where (). Just having trouble finding the right syntax.

+13
source share
4 answers

In cases where you have several branching operators, it is best to create a function that takes a string and then apply it along axis=1 . This is usually much faster than iterating through the lines.

 def func(row): if row['mobile'] == 'mobile': return 'mobile' elif row['tablet'] =='tablet': return 'tablet' else: return 'other' df['combo'] = df.apply(func, axis=1) 
+26
source

I tried the following and the result was much faster. Hope this is helpful to others.

 df['combo'] = 'other' df.loc[df['mobile'] == 'mobile', 'combo'] = 'mobile' df.loc[df['tablet'] == 'tablet', 'combo'] = 'tablet' 
+31
source

ELIF logic can be implemented using np.select or np.where :

 import numpy as np df['combo'] = np.select([df.mobile == 'mobile', df.tablet == 'tablet'], ['mobile', 'tablet'], default='other') # or df['combo'] = np.where(df.mobile == 'mobile', 'mobile', np.where(df.tablet == 'tablet', 'tablet', 'other')) 

Sample data + output:

  mobile tablet combo 0 mobile bar mobile 1 foo tablet tablet 2 foo nan other 3 mobile tablet mobile 4 mobile nan mobile 5 foo tablet tablet 6 mobile bar mobile 7 mobile tablet mobile 8 mobile bar mobile 9 mobile nan mobile 
+4
source

Adding np.where solution:

 df['col1']= np.where(df['col'] < 3, 1,np.where( (df['col'] >3 )& (df['col'] <5),2,3)) 

The general logic is:

 np.where(Condition, 'true block','false block'). 

With each true / false block, you can in turn be invested again.

Also, check out & for ANDing! (not 'and') ANDing! (not 'and') ANDing! (not 'and') ANDing! (not 'and')

0
source

Source: https://habr.com/ru/post/951578/


All Articles