Python:如何填充依赖于前一个值(前一行)的Pandas列?

时间:2017-02-12 02:38:54

标签: python pandas

我正在构建一个财务应用。我的位置取决于前一个位置(上一行)以及'信号'列(同一行)

DataFrame称为SPY。

position_arr = []
position = 0
for row in SPY['signal']:
    if row=='BUY' and position == 0:
        position = 1
    elif row=='SELL' and position == 0:
        position = -1
    elif row=='CLOSE SELL' and position == -1:
        position = 0
    elif row=='CLOSE BUY' and position == 1:
        position = 0
    position_arr.append(position)

SPY['position']=position_arr

有更好更有效的方法吗?

2 个答案:

答案 0 :(得分:2)

您可以移动position列并在列轴上使用apply()

def apply_func(row):
    if row['signal']=='BUY' and row['pos_shifted'] == 0:
        position = 1
    elif row['signal']=='SELL' and row['pos_shifted'] == 0:
        position = -1
    elif row['signal']=='CLOSE SELL' and row['pos_shifted'] == -1:
        position = 0
    elif row['signal']=='CLOSE BUY' and row['pos_shifted'] == 1:
        position = 0
    return position

SPY['pos_shift'] = SPY['position'].shift()
SPY['position'] = SPY.apply(apply_func, axis=1)

答案 1 :(得分:1)

您可以在信号'上使用apply列并使用变量来保存先前的值。

prev_val = None  #if you don't know what should be the first value 

def check_condition(current_val):
    global prev_val
    val = 0
    if prev_val is not None:
        if current_val == 'BUY' and prev_val == 0:
            val = 1
        elif current_val == 'SELL' and prev_val == 0:
            val = -1
        elif current_val == 'CLOSE SELL' and prev_val == -1:
            val = 0
        elif current_val == 'CLOSE BUY' and prev_val == 1:
            val = 0
    else:  # handle the first row case separately
        val = 0  # TODO: what is the value for the first row?
    prev_val = val
    return val

df['position'] = df['signal'].apply(check_condition)