KUOWEI0313
KUOWEI0313

Reputation: 41

How to create a new column from other column by condition

I have a dataframe like this

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          

and I hope I can create a new column by buy_action's value, if buy_action is 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

will take enterhigh, if it's -1, take exithigh

I tried using numpy select like

condition = ((df['buy_action'] == 1),
             (df['buy_action'] == -1))
value = [df['enterhigh'],df['exithigh']]
df['action_price'] = np.select(condition,value)

but it's not working

Thank you for your helping!!

Upvotes: 2

Views: 61

Answers (4)

Pygirl
Pygirl

Reputation: 13349

Using numpy select:

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

Upvotes: 1

RaJa
RaJa

Reputation: 1567

You could use a list comprehension:

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

Upvotes: 1

Mahamadou
Mahamadou

Reputation: 797

That's a good use case for the apply method, that'll take a row and returns a new value :

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

Upvotes: 1

Mustafa Aydın
Mustafa Aydın

Reputation: 18296

What about np.where:

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

It takes values from enter_high if buy_action is 1, else it takes from exit_high.

And we get

                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

Note that any value of buy_action that is not 1 (e.g. -1, 2) will yield values from exithigh.

Upvotes: 1

Related Questions