将 ndarray 除以标量 - Numpy / Python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/21797889/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Divide ndarray by scalar - Numpy / Python
提问by pceccon
I'm just wondering how could I do such thing without using loops.
我只是想知道如何在不使用循环的情况下做这样的事情。
I made a simple test trying to call a division as we do with a numpy.array, but I got the same ndarray.
我做了一个简单的测试,试图调用一个除法,就像我们对 numpy.array 所做的那样,但我得到了相同的 ndarray。
N = 2
M = 3
matrix_a = np.array([[15., 27., 360.],
            [180., 265., 79.]])
matrix_b = np.array([[.5, 1., .3], 
            [.25, .7, .4]])
matrix_c = np.zeros((N, M), float)
n_size = 360./N
m_size = 1./M
for i in range(N):
    for j in range(M):
        n = int(matrix_a[i][j] / n_size) % N
        m = int(matrix_b[i][j] / m_size) % M
        matrix_c[n][m] += 1 
matrix_c / (N * M)
print matrix_c  
I guess this should be pretty simple. Any help would be appreciated.
我想这应该很简单。任何帮助,将不胜感激。
采纳答案by Nigel Tufnel
I think that you want to modify matrix_cin-place:
我认为你想matrix_c就地修改:
matrix_c /= (N * M)
Or probably less effective:
或者可能不太有效:
matrix_c = matrix_c / (N * M) 
Expression matrix_c / (N * M)doesn't change matrix_c- it creates a new matrix.
表达式matrix_c / (N * M)不会改变matrix_c- 它会创建一个新矩阵。
回答by Kenan
Another solution would be to use numpy.divide
另一种解决方案是使用 numpy.divide
matric_c = np.divide(matrix_c, N*M)
Just make sure N*M is a float in case your looking for precision.
只要确保 N*M 是一个浮点数,以防您寻找精度。

