简体   繁体   English

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

[英]Python: How to populate Pandas column that depends on the previous value (previous row)?

I am building a financial app. 我正在构建一个财务应用程序。 My position depends on the previous position (previous row) and also on the 'signal' column (same row) . 我的位置取决于先前的位置(前一行)以及'信号'列(同一行)

The DataFrame is called SPY. 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

Is there a better and more efficient way to do this? 有没有更好,更有效的方法来做到这一点?

You could shift the position column and use apply() on the column axis: 您可以移动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)

You can use apply on 'signal' column and use a variable to hold the previous value. 您可以在'signal'列上使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM