Python 熊猫:在列后面附加条件
我有一个样本时间序列数据(股票),如下所示:Python 熊猫:在列后面附加条件,python,pandas,Python,Pandas,我有一个样本时间序列数据(股票),如下所示: 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
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
我想根据以下条件添加一个新列GAP
:
- 如果当前开放日高于前一天,则
GAP=up
- 如果当前开放日低于前一天的最后一天,则
GAP=down
- 否则,
。(或者,向上可以更改为+1,向下可以更改为-1,取消选中可以更改为0。)GAP=unch
我可以用if和for循环来实现这一点,但这会降低Pandas中verctorized操作的效率。有人能帮忙吗 使用嵌套的
np。其中
调用:
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'))
将numpy导入为np
df['GAP']=np.where(df['PX_OPEN']>df['PX_LAST'].shift(),'up',
np.where(df['PX_OPEN']
使用嵌套的np。其中
调用:
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'))
将numpy导入为np
df['GAP']=np.where(df['PX_OPEN']>df['PX_LAST'].shift(),'up',
np.where(df['PX_OPEN']