Python 如何根据条件从其他列创建新列

Python 如何根据条件从其他列创建新列,python,pandas,Python,Pandas,我有一个这样的数据帧 enterhigh exithigh buy_action 4149.99 4044.00 1.0 4211.08 4068.50 -1.0 4041.23 3750.08 1.0 4265.80 4103.51 -1.0 4250.94 4136.3

我有一个这样的数据帧

enterhigh    exithigh        buy_action                                                
4149.99      4044.00         1.0
4211.08      4068.50        -1.0
4041.23      3750.08         1.0
4265.80      4103.51        -1.0
4250.94      4136.33         1.0          
我希望我可以通过buy_action的值创建一个新列,如果buy_action为1,则为new column

enterhigh    exithigh        buy_action   action_price                                                
4149.99      4044.00         1.0          4149.99
4211.08      4068.50        -1.0          4068.50
4041.23      3750.08         1.0          4041.23
4265.80      4103.51        -1.0          4103.51
4250.94      4136.33         1.0          4250.94
将使用enterhigh,如果为-1,则使用exighth

我试着使用numpy select like

condition = ((df['buy_action'] == 1),
             (df['buy_action'] == -1))
value = [df['enterhigh'],df['exithigh']]
df['action_price'] = np.select(condition,value)
但它不起作用

谢谢你的帮助

那么:

df[“动作价格”]=np.where(df.buy\u动作==1,df.enterhigh,df.exighth)
如果
buy\u action
1
,则从
enter\u high
获取值,否则从
exit\u high
获取值

我们得到了

                date  enterhigh  exithigh  buy_action  action_price
2017-08-20  06:00:00    4149.99   4044.00         1.0       4149.99
2017-08-20  23:00:00    4211.08   4068.50        -1.0       4068.50
2017-08-22  17:00:00    4041.23   3750.08         1.0       4041.23
2017-08-23  19:00:00    4265.80   4103.51        -1.0       4103.51
2017-08-24  21:00:00    4250.94   4136.33         1.0       4250.94

请注意,
buy_action
的任何值如果不是
1
(例如
-1
2
)将从
exighth

中生成值,这是apply方法的一个很好的用例,它将获取一行并返回一个新值:

df[“操作价格”]=df.apply(如果x.buy\u操作==1,则lambda x:x.enterhigh,否则x.exighth,轴=1)

您可以使用列表理解:

df['new column'] = [df.loc[i, 'exithigh'] for i in df.index if df.loc[i, 'buy_action']>0 else -1]

使用
numpy选择

df['action_price'] = np.select([df.buy_action.eq(1)], [df.enterhigh], default=df.exithigh)

numpy select如何不工作?请解释。事实上,我认为如果我理解numpy select more,它会起作用。当我编写上述代码时,action_price完全是零填充的。当然,我是新来的,我希望我以正确的方式完成它,再次感谢。