pandas :将一个矩阵的值除以另一个带有相应子索引的值 [英] Pandas: divide value of one matrix by another with respective subindex

查看:115
本文介绍了 pandas :将一个矩阵的值除以另一个带有相应子索引的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果A值的子索引是B的索引,我想将矩阵A的每个值除以矩阵B的值.

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.

举个例子: 答:

         (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

和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

我想要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

我在Panda中按组寻找方法,但是我没有找到正确的方法.预先谢谢你.

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

推荐答案

我认为您需要

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

这篇关于 pandas :将一个矩阵的值除以另一个带有相应子索引的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆