简体   繁体   English

根据 if 和现有列在 pandas 中创建新列

[英]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假设我有 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.我想设置一个新列 df['salessup'] 如果它的值不是'x',它应该等于 SalesmanA,如果它是 x 到 salesmanB 新列应该像 ['salessup']=['Jack', 'John','Mike','David'] 提前谢谢你。

Try np.where试试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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM