Search code examples
pythonpandasmulti-index

Multiindex fill columns


I have a dataframe X filled with data, where the column names denote currencies:

enter image description here

And an empty dataframe Y with a multi-index. The first level is the country, and the second level is the currency:

enter image description here

How can I fill Y with the corresponding data in X, i.e. place the USD column from X to the (US,USD) column in Y etc?

I did try:

for column in rates.columns: 
df2.loc[:, (slice(None), [column])]  = rates[column] 

Which returns

ValueError: Must have equal len keys and value when setting with an iterable

I think it is because we have four EUR columns on Y


Solution

  • IIUC, let's try using pd.DataFrame.align:

    df.align(df2, axis=None, level=1)[0]  
    

    Output:

                  US  CA  AU   UK  IT  CH  FR  SP  NL  SW    JP  HK  KO  TW
                 USD CAD AUD  GBP EUR CHF EUR EUR EUR SEK   JPY HKD KRW TWD
    1969-12-13  8.01 NaN NaN  8.0 NaN NaN NaN NaN NaN NaN  6.25 NaN NaN NaN
    1970-01-01  8.01 NaN NaN  8.0 NaN NaN NaN NaN NaN NaN  6.25 NaN NaN NaN
    1970-01-02  7.92 NaN NaN  8.0 NaN NaN NaN NaN NaN NaN  6.25 NaN NaN NaN
    1970-01-05  7.91 NaN NaN  8.0 NaN NaN NaN NaN NaN NaN  6.25 NaN NaN NaN
    1970-01-06   NaN NaN NaN  NaN NaN NaN NaN NaN NaN NaN   NaN NaN NaN NaN