Pandas: split the value of one matrix by another with the appropriate subindex

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

Let's take an 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 the first column 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 other columns, eg. second:

        (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 searched in a group for an approach in Panda, but I didn't find something like that. Thank you in advance.

+2


source to share


1 answer


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

      

+2


source







All Articles