2

I would like to divide each value of the matrix A with the value of matrix B if the sub-index of the A's value is the index of B.

Take a example: A:

         (A, 1)    (A, 2)    (B, 1)    (B, 2)    (B, 3)
(A, 1)  0.102179  0.024903  0.598978  0.141483  0.904239
(A, 2)  0.563096  0.765552  0.608203  0.339500  0.671222
(B, 1)  0.867550  0.432277  0.311634  0.165246  0.046199
(B, 2)  0.813666  0.846750  0.145595  0.996221  0.209762
(B, 3)  0.834860  0.176203  0.886546  0.506550  0.883405

And B:

   (A, 1)    (A, 2)    (B, 1)    (B, 2)    (B, 3)
1  0.996778  0.801235  0.120127  0.863761  0.519856
2  0.757775  0.706402  0.428906  0.479940  0.001049

I would like for the first column of A:

         (A, 1)    
(A, 1)  0.102179/0.996778  
(A, 2)  0.563096/0.757775
(B, 1)  0.867550/0.996778
(B, 2)  0.813666/0.757775
(B, 3)  0.834860

Same idea for the other columns, e.g. the second one:

        (A, 2)
(A, 1)  0.024903/0.801235
(A, 2)  0.765552/0.706402
(B, 1)  0.432277/0.801235
(B, 2)  0.846750/0.706402
(B, 3)  0.176203

I was looking for in the group by approach in Panda, but I haven't find something right. Thanks you in advance.

Cyril
  • 485
  • 4
  • 15

1 Answers1

2

I think you need div:

df = df1.div(df2, level=1, fill_value=1)
print (df)
            A                   B                      
            1         2         1         2           3
A 1  0.102509  0.031081  4.986206  0.163799    1.739403
  2  0.743091  1.083734  1.418033  0.707380  639.868446
B 1  0.870354  0.539513  2.594204  0.191310    0.088869
  2  1.073757  1.198680  0.339457  2.075720  199.963775
  3  0.834860  0.176203  0.886546  0.506550    0.883405

print (0.102179/0.996778 )
0.10250928491599935
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252