如何根据先前状态在 pandas 数据框中创建列?

How to create a column in a pandas dataframe based on a previous state?

我有一个带有时间序列索引的 pandas 数据框。 一列包含买入信号,另一列包含卖出信号。

buy     0 0 1 0 1 1 0 1 1 1 0 1 0 0 0 0 0 0 0 0 
sell    0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 1 0

我想给这个简单的模型加一个状态:任何时候最多有1只股票:只有当你目前什么都没有的时候才买,当你有股票的时候才卖。

buy     0 0 1 0 1 1 0 1 1 1 0 1 0 0 0 0 0 0 0 0 
sell    0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 1 0
wallet  0 0 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0

如何根据 df['buy']df['sell'] 创建 df['wallet'] 列?

这不是最漂亮的解决方案,但我相信它能满足您的需求。

import pandas as pd

df = pd.DataFrame({ 'buy':  [0,0,0,1,0,1,1,1,1,1,0,0,0,0,0,0], 
                    'sell': [0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1]   })


df['wallet'] = pd.np.where(df['buy'] - df['sell'] < 0, 0, df['buy'].cumsum().count() - df['sell'].cumsum())
df.loc[df['wallet'] > 1, 'wallet'] = 1
import pandas as pd

wallet = 0


def create_wallet(df_line):
    global wallet

    if df_line['buy']:
        wallet = 1

    elif df_line['sell']:
        wallet = 0

    return wallet


df = pd.DataFrame(
{'buy': [0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], 'sell': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1]})
df['wallet'] = df.apply(create_wallet, axis=1)