Home > Mobile >  Name and join 2 multi index dataframe after operation is done
Name and join 2 multi index dataframe after operation is done

Time:09-18

Have the following multi index data frame, df.

I performed a 20 day moving average operation on the df[‘Close’] with the following code, ma20.

How do I append m20 to df as a multi index data frame?

I should have 3 level 0 columns, ['Adj Close','Close', ‘ma20’], each with the 3 tickers, ['MSFT','AAPL','AMZN'], at level 1 columns.

The answer should also not require me to type out all the tickers manually.

import yfinance as yf

df = yf.download(['MSFT','AAPL','AMZN'], start="2022-01-01", end="2022-09-01").loc[:,['Adj Close','Close']]

ma20 = df['Close'].sort_index(ascending=True).rolling(20, min_periods=20).mean()

pd.concat([df,ma20], axis=1)????

enter image description here enter image description here

CodePudding user response:

It's not very elegant solution, but should work, the idea is to specify explicitly the multiindex names for new columns:

df[[('Mean', col) for col in ma20.columns]] = ma20

UPDATE:

If you want to use concat() method, you need firstly to add another column index level to ma20. The way you can do this looks counter-intuitive up to me:

pd.concat((df, pd.concat({'Mean': ma20}, axis=1)), sort=False, axis=1)

The purpose of pd.concat({'Mean': ma20}, axis=1)) is just to add another index level to the columns of ma20

  • Related