我如何计算数组中的值与python中数组的总和之比? [英] How can I calculate the ratio of a value in array to the sum of array in python?
本文介绍了我如何计算数组中的值与python中数组的总和之比?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的数组:
array =[[1,2,3],
[5,3,4],
[6,7,2]]
我想为每个成员计算它们与行总和的比率.
and for each member I would like to calculate the ratio of them to the sum of the row.
因此,我在提出的样本中提出问题的结果是:
Therefore, the result of my question in proposed sample is:
result = [[1/(1+2+3),2/(1+2+3),3/(1+2+3)],
[5/(5+3+4),3/(5+3+4),4/(5+3+4)],
[6/(6+7+2),7/(6+7+2),2/(6+7+2)]]
我编写了以下代码,但由于两个运算符的形状不同而无法正常工作
I write the following code but it does not work because two operators have different shape:
array/array.sum(array, axis=1)
推荐答案
您可以在进行求和时指定keepdim=True
,然后有一个二维数组作为结果,而每行代表行总和:
You can specify keepdim=True
while doing the sum, and then you have a 2d array as result while each row stands for the row sum:
array = np.array([[1,2,3],
[5,3,4],
[6,7,2.]])
array/array.sum(1, keepdims=True)
#array([[ 0.16666667, 0.33333333, 0.5 ],
# [ 0.41666667, 0.25 , 0.33333333],
# [ 0.4 , 0.46666667, 0.13333333]])
这篇关于我如何计算数组中的值与python中数组的总和之比?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文