如何在python中规范化二维numpy数组不那么冗长? [英] How to normalize a 2-dimensional numpy array in python less verbose?
本文介绍了如何在python中规范化二维numpy数组不那么冗长?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个 3 乘以 3 的 numpy 数组
Given a 3 times 3 numpy array
a = numpy.arange(0,27,3).reshape(3,3)
# array([[ 0, 3, 6],
# [ 9, 12, 15],
# [18, 21, 24]])
对我想到的二维数组的行进行归一化
To normalize the rows of the 2-dimensional array I thought of
row_sums = a.sum(axis=1) # array([ 9, 36, 63])
new_matrix = numpy.zeros((3,3))
for i, (row, row_sum) in enumerate(zip(a, row_sums)):
new_matrix[i,:] = row / row_sum
一定有更好的方法,不是吗?
There must be a better way, isn't there?
也许要澄清一下:我的意思是规范化,每行条目的总和必须是一个.但我认为大多数人都会清楚这一点.
Perhaps to clearify: By normalizing I mean, the sum of the entrys per row must be one. But I think that will be clear to most people.
推荐答案
广播对此非常有用:
row_sums = a.sum(axis=1)
new_matrix = a / row_sums[:, numpy.newaxis]
row_sums[:, numpy.newaxis]
将 row_sums 从 (3,)
重塑为 (3, 1)
.当您执行a/b
时,a
和b
会相互广播.
row_sums[:, numpy.newaxis]
reshapes row_sums from being (3,)
to being (3, 1)
. When you do a / b
, a
and b
are broadcast against each other.
您可以在此处了解有关广播的更多信息强> 甚至更好在这里.
You can learn more about broadcasting here or even better here.
这篇关于如何在python中规范化二维numpy数组不那么冗长?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文