在2d数组中沿轴的Numpy百分比

don*_*lan 4 python arrays numpy

我有一个计数矩阵,

import numpy as np
x = np.array([[ 1,2,3],[1,4,6],[2,3,7]])
Run Code Online (Sandbox Code Playgroud)

我需要沿轴的总百分比= 1:

for i in range(x.shape[0]):
    for j in range(x.shape[1]):
        x[i,j] = x[i,j] / np.sum(x[i,:])
Run Code Online (Sandbox Code Playgroud)

以numpy广播形式.

目前,我有:

x_sums = np.sum(x,axis=1)
for j in range(x.shape[1]):
     x[:,j] = x[:,j] / x_sums[:]
Run Code Online (Sandbox Code Playgroud)

这使得大部分复杂性变成了numpy代码...但是一个numpy one liner最好.

也,

def percentages(a):
    return a / np.sum(a)

x_percentages = np.apply_along_axis(percentages,1,x)
Run Code Online (Sandbox Code Playgroud)

但这仍然涉及python.


 np.linalg.norm
Run Code Online (Sandbox Code Playgroud)

就发生的事情而言,非常接近,但他们只有8个硬编码规范,其中不包括总数的百分比.

然后就是np.percentile,它再次接近......但它正在计算排序的百分位数.

小智 9

x /= x.sum(axis=1, keepdims=True)
Run Code Online (Sandbox Code Playgroud)

Altough x应该有一个浮点dtype,以便正常工作.

更好的可能是:

x = np.true_divide(x, x.sum(axis=1, keepdims=True))
Run Code Online (Sandbox Code Playgroud)