简体   繁体   English

编写此 numpy 代码的更有效方法

[英]More efficient way to write this numpy code

Hi I'd like to create a 10 x 5 matrix with the first column filled with 1 to 10 and the subsequent columns filled with 2, 3, 4 and 5 times the values of the first column.嗨,我想创建一个 10 x 5 矩阵,第一列填充 1 到 10,后续列填充第一列值的 2、3、4 和 5 倍。

I've made things work with the following code, but is there a shorter way to do this?我已经使用以下代码完成了工作,但是有没有更短的方法可以做到这一点?

import numpy as np
mat = np.zeros([10,5])
mat[:,0] = np.arange(1,11)
mat[:,1] = np.dot(mat[:,0],2)
mat[:,2] = np.dot(mat[:,0],3)
mat[:,3] = np.dot(mat[:,0],4)
mat[:,4] = np.dot(mat[:,0],5)

I think you can achieve this by outer product.我认为你可以通过外部产品来实现这一点。

Try:尝试:

import numpy as np

a = np.arange(1, 11).reshape(-1, 1)    # column vector (1,2,3,...,10)
b = np.arange(1, 6).reshape(1, -1)     # row vector (1,2,3,...,5)
np.matmul(a, b)                        # matrix of entries of multiplication of the indices (1-based indices)

or the one-liner:或单线:

np.arange(1, 11).reshape(-1, 1) * np.arange(1, 6).reshape(1, -1)

This works for me:这对我有用:

>>> np.array([np.array([1,2,3,4,5]) * i for i in range(1,11)])
array([[ 1,  2,  3,  4,  5],
       [ 2,  4,  6,  8, 10],
       [ 3,  6,  9, 12, 15],
       [ 4,  8, 12, 16, 20],
       [ 5, 10, 15, 20, 25],
       [ 6, 12, 18, 24, 30],
       [ 7, 14, 21, 28, 35],
       [ 8, 16, 24, 32, 40],
       [ 9, 18, 27, 36, 45],
       [10, 20, 30, 40, 50]])

This is exactly what builtin numpy outer does:这正是内置numpy outer所做的:

>>> np.outer(np.arange(1, 11), np.arange(1, 6))
array([[ 1,  2,  3,  4,  5],
       [ 2,  4,  6,  8, 10],
       [ 3,  6,  9, 12, 15],
       [ 4,  8, 12, 16, 20],
       [ 5, 10, 15, 20, 25],
       [ 6, 12, 18, 24, 30],
       [ 7, 14, 21, 28, 35],
       [ 8, 16, 24, 32, 40],
       [ 9, 18, 27, 36, 45],
       [10, 20, 30, 40, 50]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM