I want to divide all columns in a dataframe with a multiindex by another dataframe with a multiindex, one level smaller. The first two levels of moth indices are identical. And the third level should be broadcasted.
df_0 = pd.DataFrame( {
"col0": [ 1, 2, 3, 4, 5 ],
"col1": [ 3, 6, 9, 12, 15 ],
} )
df_0.index = pd.MultiIndex.from_tuples(
[ ( "A", "a", 0 ), ( "A", "a", 1 ), ( "A", "b", 0 ), ( "A", "b", 1 ), ( "B", "b", 0 ) ]
)
df_0.index.names = [ "foo", "bar", "baz" ]
df_1 = pd.DataFrame( {
"stuff": [ 100, 110, 120, 130, ],
} )
df_1.index = pd.MultiIndex.from_tuples(
[ ( "A", "a" ), ( "A", "b" ), ( "B", "a" ), ( "B", "b" ) ]
)
df_1.index.names = [ "foo", "bar" ]
print( df_0 )
print( df_1 )
This gives me the following two dataframes df_0
col0 col1
foo bar baz
A a 0 1 3
1 2 6
b 0 3 9
1 4 12
B b 0 5 15
and df_1
stuff
foo bar
A a 100
b 110
B a 120
b 130
If I try to divide each column value by the respective stuff column I get an error message
print( df_0.div( df_1 ) )
Join on level between two MultiIndex objects is ambiguous
What I want to achieve is the following result:
col0 col1
foo bar baz
A a 0 1/100 3/100
1 2/100 6/100
b 0 3/110 9/110
1 4/110 12/110
B b 0 5/130 15/130