P. Sheih
P. Sheih

Reputation: 13

Pandas: appending column with condition

I have a sample time series data (stock) as below:

                 Date  PX_OPEN  PX_LAST
Date                                   
2011-01-03 2011-01-03    31.18    31.26
2011-01-04 2011-01-04    31.42    31.02
2011-01-05 2011-01-05    31.10    30.54
2011-01-06 2011-01-06    30.66    30.54
2011-01-07 2011-01-07    31.50    30.66
2011-01-10 2011-01-10    30.82    30.94

I would like to add a new column GAP based on the following conditions:

I can do this with if and for loop, but that would defeat the efficiency of verctorized operation in Pandas. Can anyone help?

Upvotes: 0

Views: 81

Answers (1)

IanS
IanS

Reputation: 16251

Use nested np.where calls:

import numpy as np
df['GAP'] = np.where(df['PX_OPEN'] > df['PX_LAST'].shift(), 'up',
            np.where(df['PX_OPEN'] < df['PX_LAST'].shift(), 'down', 'unch'))

Upvotes: 2

Related Questions