Python – Create an IF statement in Python to view the output of previous IF statements

Create an IF statement in Python to view the output of previous IF statements… here is a solution to the problem.

Create an IF statement in Python to view the output of previous IF statements

I’m having trouble creating an IF statement that does the following:

  • Buy if C1 = Buy
  • Sell if C2 = Sell
  • If C1 & C2 = nan, the current cell = previous cell

Take a look at the example below. I would like to create a column like “C3”.

Sample dataset:

index  C1    C2
0      Buy   nan
1      nan   nan
2      nan   Sell
3      nan   nan
4      Buy   nan
5      nan   Sell
6      nan   Sell
7      nan   nan
8      nan   nan
9      Buy   nan
10     nan   Sell

Output:

index  C1    C2    C3
0      Buy   nan   Buy
1      nan   nan   Buy
2      nan   Sell  Sell
3      nan   nan   Sell
4      Buy   nan   Buy
5      nan   Sell  Sell
6      nan   Sell  Sell
7      nan   nan   Sell
8      nan   nan   Sell
9      Buy   nan   Buy
10     nan   Sell  Sell

Solution

You can use pd. DataFrame.ffill follows axis=1 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

Related Problems and Solutions