I have a multiindex DataFrame with level=0
being the date and level=1
being the stock index, and the columns being the constituent tickers of each stock index. The values are tallies recording when the ticker is in the index (1.0
) and when it's not (NaN
). The DataFrame is as follows:
df:
ticker TSLA AAPL MSFT GLD FB BRK JPM
Date symbol
2022-01-01 SPY 1.0 1.0 1.0 NaN NaN 1.0 1.0
NASDAQ 1.0 1.0 1.0 NaN NaN NaN NaN
2022-01-02 SPY 1.0 1.0 1.0 NaN NaN 1.0 1.0
NASDAQ 1.0 1.0 1.0 NaN NaN NaN NaN
DOW NaN NaN 1.0 1.0 NaN 1.0 1.0
2022-01-03 SPY 1.0 1.0 NaN NaN NaN 1.0 1.0
2022-01-04 DOW NaN NaN 1.0 1.0 NaN 1.0 1.0
...
2022-01-30 SPY 1.0 1.0 NaN NaN NaN 1.0 1.0
NASDAQ 1.0 1.0 1.0 NaN NaN NaN NaN
2022-02-01 SPY 1.0 1.0 NaN NaN NaN 1.0 1.0
DOW NaN NaN 1.0 1.0 NaN 1.0 1.0
...
2022-02-28 SPY 1.0 1.0 1.0 NaN NaN 1.0 1.0
NASDAQ 1.0 1.0 1.0 NaN NaN NaN NaN
DOW NaN NaN 1.0 1.0 NaN 1.0 1.0
2022-03-01 SPY 1.0 1.0 1.0 NaN NaN 1.0 1.0
NASDAQ 1.0 1.0 1.0 NaN NaN NaN NaN
DOW NaN NaN 1.0 1.0 NaN 1.0 1.0
What I want is to forward-fill the tally (1.0
) for the tickers based on the previous tally for the symbol on the following basis:
- SPY -> Daily tally
- NASDAQ -> Monthly tally
- DOW -> Quarterly tally
and then I just want to take the values of the symbol at these frequencies (i.e. daily values for SPY, the monthly value for NASDAQ, the quarterly value for DOW).
So the final DataFrame should look like this:
df_final:
ticker TSLA AAPL MSFT GLD FB BRK JPM
Date symbol
2022-01-01 SPY 1.0 1.0 1.0 NaN NaN 1.0 1.0
NASDAQ 1.0 1.0 1.0 NaN NaN NaN NaN
2022-01-02 SPY 1.0 1.0 1.0 NaN NaN 1.0 1.0
2022-01-03 SPY 1.0 1.0 NaN NaN NaN 1.0 1.0
...
2022-01-30 SPY 1.0 1.0 NaN NaN NaN 1.0 1.0
2022-02-01 SPY 1.0 1.0 NaN NaN NaN 1.0 1.0
NASDAQ 1.0 1.0 1.0 NaN NaN NaN NaN
...
2022-03-01 SPY 1.0 1.0 1.0 NaN NaN 1.0 1.0
NASDAQ 1.0 1.0 1.0 NaN NaN NaN NaN
DOW NaN NaN 1.0 1.0 NaN 1.0 1.0
How can this be achieved using pandas? (i.e. I want to minimize the amount of loops)