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 :
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