2
$\begingroup$

I would like to fill the missing data using the value from the previous trading day of the same stock. In this example, the AAPL stock should be 100.

I've tried with fillna but I am not able to pick a specific row based on the stock.

My data:

date       stock   price
22/12/20   MSFT    87
22/12/20   AAPL    99
22/12/20   FCA     81
23/12/20   MSFT    90
23/12/20   AAPL    100
23/12/20   FCA     80
24/12/20   MSFT    91
24/12/20   AAPL   NaN
24/12/20   FCA     78
$\endgroup$

1 Answer 1

1
$\begingroup$

You can groupby by 'stock', forward fill missing values with ffill and use its result in fillna. For example:

date       stock   price
22/12/20   MSFT    87
22/12/20   AAPL    99
22/12/20   FCA     81
23/12/20   MSFT    NaN
23/12/20   AAPL    100
23/12/20   FCA     80
24/12/20   MSFT    91
24/12/20   AAPL    NaN 
24/12/20   FCA     NaN

df.fillna(df.groupby('stock').ffill())

Result:

       date stock  price
0  22/12/20  MSFT   87.0
1  22/12/20  AAPL   99.0
2  22/12/20   FCA   81.0
3  23/12/20  MSFT   87.0
4  23/12/20  AAPL  100.0
5  23/12/20   FCA   80.0
6  24/12/20  MSFT   91.0
7  24/12/20  AAPL  100.0
8  24/12/20   FCA   80.0
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.