Creating an IF statement in Python that looks at previous IF statement output

前端 未结 3 963
忘掉有多难
忘掉有多难 2021-01-20 16:30

I am having difficulty creating an IF statement that does the following:

  • If C1 = Buy, then Buy
  • If C2 = Sell, then Sell
  • If C1 & C2 = nan,
3条回答
  •  死守一世寂寞
    2021-01-20 17:08

    Here's a tidy way to do it using Pandas: Swap all the NaN for empty strings, and return whatever string value is in each row. If a row is empty, return what came before it.

    import pandas as pd
    
    def decide(data):
        if len(data.sum()):
            return data.sum()
        return decide(df.iloc[data.name - 1])
    
    df.fillna("", inplace=True)
    df.apply(decide, axis=1)
    

    Output:

    index
    0      Buy
    1      Buy
    2     Sell
    3     Sell
    4      Buy
    5     Sell
    6     Sell
    7     Sell
    8     Sell
    9      Buy
    10    Sell
    dtype: object
    

    Note: Making a couple of assumptions here. First, assuming only Buy or Sell occurs in a row. Second, assuming first row is not empty.

    Data:

    df = pd.read_clipboard(index_col="index") # copied from OP
    

提交回复
热议问题