Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

creating new column in pandas based on if and existing column

I have found different answers to this question but none pulling data from existing column.
Let’s say I have DataFrame

purchase=
{'date':['11/03/2021','12/03/2021','14/03/2021','11/03/2021'],
'price':[300, 400,200, 200],
'currency':['eur', 'usd','usd','usd'],
'qty':[200, 300, 400, 500],
'salesmanA':['Jack', 'x', "Mike", 'x'],
'salesmanB':['x', 'John', "x", 'David']}
df=pd.DataFrame(purchase)

I want to set a new column df[‘salessup’] which should be equal to SalesmanA if its value is not ‘x’, and if it’s x to salesmanB
new columns should be like [‘salessup’]=[‘Jack’,’John’,’Mike’,’David’]
thank you in advance.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try np.where

df['out'] = np.where(df.salesmanA=='x',df.salesmanB,df.salesmanA)
df
Out[450]: 
         date  price currency  qty salesmanA salesmanB    out
0  11/03/2021    300      eur  200      Jack         x   Jack
1  12/03/2021    400      usd  300         x      John   John
2  14/03/2021    200      usd  400      Mike         x   Mike
3  11/03/2021    200      usd  500         x     David  David
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading