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, then the current cell = previous cell
Please see an example below. I am hoping 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
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.Output:
Note: Making a couple of assumptions here. First, assuming only
Buy
orSell
occurs in a row. Second, assuming first row is not empty.Data:
You can use
pd.DataFrame.ffill
alongaxis=1
followed bypd.Series.ffill
:Instead of doing the previous if statement, you can simply look at what has been previously put into the
c3
list (as that is a result of the previous if statement).Here is an example of how you can achieve this in python:
Output:
['Buy', 'Buy', 'Sell', 'Sell', 'Buy', 'Sell', 'Sell', 'Sell', 'Sell', 'Buy', 'Sell']