如何正常化蟒蛇不再那么繁琐的二维数组numpy的? [英] How to normalize a 2-dimensional numpy array in python less verbose?
问题描述
给定一个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]])
要规范化2维数组我想到的行
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?
也许是为了clearify:通过正火我的意思是,每行entrys的总和必须的。但我认为,这将是明确的大多数人。
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.
您可以了解更多关于广播 这里 甚至更好<一个href=\"http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html?highlight=broadcasting#numpy.doc.broadcasting\">here.
You can learn more about broadcasting here or even better here.
这篇关于如何正常化蟒蛇不再那么繁琐的二维数组numpy的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!