Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas fill Mutliindex column data frame from single index column data frame

I have two data frames with same row index.

First dataframe :

df1 = pd.DataFrame(index=['a', 'b', 'c'], columns=pd.MultiIndex.from_product([['2023-12-31','2024-01-31'], ['myvalue1', 'myvalue2']]))

Second dataframe :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df2 = pd.DataFrame(index=['a', 'b', 'c'], data=
                   {'myvalue1':[2,3, 4], 'myvalue2':[6,7,8]})

Remembering that row indices are the same, I wanted to fill first dataframe with second, like that :

df1.loc[:,(slice(None),'myvalue1')] = df2['myvalue1']
df1.loc[:,(slice(None),'myvalue2')] = df2['myvalue2']

I get the error : ValueError: Must have equal len keys and value when setting with an iterable

Expected result for df1 :

    2023-12-31          2024-01-31
   myvalue1   myvalue2  myvalue1    myvalue2
a   2          6          2           6
b   3          7          3           7
c   4          8          4           8

Do you know how to proceed (avoiding for loop) ?

Thank you

>Solution :

I’m pretty sure you can avoid using an intermediate template (i.e, the input df1) but if you can’t, here is one option with reindex/set_axis :

df1 = (
    df2
        .reindex(df1.columns.get_level_values(1), axis=1)
        .set_axis(df1.columns, axis=1)
)

Output :

  2023-12-31          2024-01-31         
    myvalue1 myvalue2   myvalue1 myvalue2
a          2        6          2        6
b          3        7          3        7
c          4        8          4        8
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading