numpy逐行除以总和 [英] numpy divide row by row sum

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

问题描述

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

这是一个例子.但我很确定有一种奇特且更有效的方法可以做到这一点:

将 numpy 导入为 npe = np.array([[0., 1.],[2., 4.],[1., 5.]])对于 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)添加一个额外的维度,以便广播将表现:

<预><代码>>>>电子数组([[ 0., 1.],[2., 4.],[ 1., 5.]])>>>e/e.sum(axis=1)[:,None]数组([[ 0. , 1. ],[ 0.33333333, 0.66666667],[ 0.16666667, 0.83333333]])

方法#2:转置快乐:

<预><代码>>>>(e.T/e.sum(axis=1)).T数组([[ 0. , 1. ],[ 0.33333333, 0.66666667],[ 0.16666667, 0.83333333]])

(如果需要,为了简洁起见,您可以删除 axis= 部分.)

方法 #3:(从 Jaime 的评论中提拔)

sum 上使用 keepdims 参数来保留维度:

<预><代码>>>>e/e.sum(axis=1, keepdims=True)数组([[ 0. , 1. ],[ 0.33333333, 0.66666667],[ 0.16666667, 0.83333333]])

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])

Result:

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

解决方案

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]])

Method #2: go transpose-happy:

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

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

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

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天全站免登陆