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

前端 未结 3 970
忘掉有多难
忘掉有多难 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 16:51

    You can use pd.DataFrame.ffill along axis=1 followed by pd.Series.ffill:

    df['C3'] = df[['C1', 'C2']].ffill(axis=1).iloc[:, -1].ffill()
    
    print(df)
    
        index   C1    C2    C3
    0       0  Buy   NaN   Buy
    1       1  NaN   NaN   Buy
    2       2  NaN  Sell  Sell
    3       3  NaN   NaN  Sell
    4       4  Buy   NaN   Buy
    5       5  NaN  Sell  Sell
    6       6  NaN  Sell  Sell
    7       7  NaN   NaN  Sell
    8       8  NaN   NaN  Sell
    9       9  Buy   NaN   Buy
    10     10  NaN  Sell  Sell
    

提交回复
热议问题