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

2024-10-01 17:23:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的数据帧

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)

但它不起作用

谢谢你的帮助


Tags: 数据numpydfnewvaluecolumnactionbuy
3条回答

^{}呢:

df["action_price"] = np.where(df.buy_action == 1, df.enterhigh, df.exithigh)

如果buy_action1,则从enter_high获取值,否则从exit_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(例如-12),将从exithigh产生值

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

df["action_price"] = df.apply(lambda x: x.enterhigh if x.buy_action == 1 else x.exithigh, axis=1)

您可以使用列表:

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

相关问题 更多 >

    热门问题