numpy逐行相除 [英] numpy divide row by row sum

查看:878
本文介绍了numpy逐行相除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将一个numpy数组行除以该行中所有值的总和?

How can I divide a numpy array row by the sum of all values in this row?

这是一个例子.但我很确定有一种理想的方法,而且效率更高:

This is one example. But I'm pretty sure there is a fancy and much more efficient way of doing this:

import numpy as np
e = np.array([[0., 1.],[2., 4.],[1., 5.]])
for row in xrange(e.shape[0]):
    e[row] /= np.sum(e[row])

结果:

array([[ 0.        ,  1.        ],
       [ 0.33333333,  0.66666667],
       [ 0.16666667,  0.83333333]])

推荐答案

方法1:使用None(或np.newaxis)添加额外的维度,以便广播能够正常工作:

Method #1: use None (or np.newaxis) to add an extra dimension so that broadcasting will behave:

>>> e
array([[ 0.,  1.],
       [ 2.,  4.],
       [ 1.,  5.]])
>>> e/e.sum(axis=1)[:,None]
array([[ 0.        ,  1.        ],
       [ 0.33333333,  0.66666667],
       [ 0.16666667,  0.83333333]])

方法2:快乐地转调:

>>> (e.T/e.sum(axis=1)).T
array([[ 0.        ,  1.        ],
       [ 0.33333333,  0.66666667],
       [ 0.16666667,  0.83333333]])

(如果需要,您可以放下axis=部分以使其简洁.)

(You can drop the axis= part for conciseness, if you want.)

方法3 :(根据Jaime的评论促成)

Method #3: (promoted from Jaime's comment)

使用sum上的keepdims参数保留尺寸:

Use the keepdims argument on sum to preserve the dimension:

>>> e/e.sum(axis=1, keepdims=True)
array([[ 0.        ,  1.        ],
       [ 0.33333333,  0.66666667],
       [ 0.16666667,  0.83333333]])

这篇关于numpy逐行相除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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