I have a pandas dataframe with historical stock prices. The issue is that some columns contain prices up to a certain date, then some blank rows, and finally price data again. This is an example:
date Stock A Stock B Stock C
0 6/30/1990 0.19 NaN Nan
1 7/31/1990 0.19 NaN Nan
2 8/31/1990 0.25 NaN 15.4
3 9/30/1990 0.34 NaN 17.4
4 10/31/1990 NaN 1.5 17
5 11/30/1990 NaN 1.8 NaN
6 12/31/1990 NaN 2.1 NaN
7 1/31/1991 NaN 2 NaN
8 2/28/1991 NaN 2.1 NaN
9 3/31/1991 NaN NaN NaN
10 4/30/1991 20.88 NaN 20.88
11 5/31/1991 18.25 NaN 18.25
12 6/30/1991 17 NaN 17
13 7/31/1991 17.25 NaN 17.25
14 8/31/1991 17.5 NaN 17.5
So what I am trying to do is in this dataframe is: -the columns like Stock A to replace all the rows above the last non-NaN value with a NaN value, in this case, replace all the values from the first 4 rows with NaNs -the columns like Stock B to leave them like that, since there are no gaps -the columns like Stock C, with more than 1 gap, keep only the last values. The resulting dataframe should be like this:
date Stock A Stock B Stock C
0 6/30/1990 NaN NaN Nan
1 7/31/1990 NaN NaN Nan
2 8/31/1990 NaN NaN NaN
3 9/30/1990 NaN NaN NaN
4 10/31/1990 NaN 1.5 NaN
5 11/30/1990 NaN 1.8 NaN
6 12/31/1990 NaN 2.1 NaN
7 1/31/1991 NaN 2 NaN
8 2/28/1991 NaN 2.1 NaN
9 3/31/1991 NaN NaN NaN
10 4/30/1991 20.88 NaN 20.88
11 5/31/1991 18.25 NaN 18.25
12 6/30/1991 17 NaN 17
13 7/31/1991 17.25 NaN 17.25
14 8/31/1991 17.5 NaN 17.5
I have tried to do it manually in Excel, since I am fairly new to Python, but given the number of columns, the process is taking too long.
The solution would be related to iterating between all the columns and check wether the condition explained above checks, and then modifying such columns.
What could be a possible solution?