您可能正在寻找np.meshgrid()
. 通过示例最容易了解它是如何工作的:
>>> import numpy as np
# Start with three different 1-D arrays, possibly with different sizes.
>>> a = np.random.random(10)
>>> b = np.random.random(15)
>>> c = np.random.random(20)
# Use np.meshgrid() to create 3-D arrays by joining the three 1-D arrays.
>>> A, B, C = np.meshgrid(a, b, c, indexing="ij")
>>> print(A.shape, B.shape, C.shape)
(10, 15, 20) (10, 15, 20) (10, 15, 20)
# It's easy to use these arrays for computations like x_ijk = a_i + b_j * c_k.
>>> X = A + B * C
# Let's do this with loops to check that we get the same result.
>>> Y = np.empty((10, 15, 20))
>>> for i in range(a.size): # i = 0, ..., 9
... for j in range(b.size): # j = 0, ..., 14
... for k in range(c.size): # k = 0, ..., 19
... Y[i,j,k] = a[i] + b[j] * c[k] # y_ijk = a_i + b_j * c_k
...
>>> np.allclose(X,Y)
True
这使您可以在所需的网格上以一种高效、易读的方式计算任何标量值函数只要记住在适用的情况下使用 NumPy 函数(例如,而不是)。f:(a,b,c)↦Rnp.sin()
math.sin()
例如,如果,首先定义网格数组, , 和, 用于获取, , 和, 和 设置。f(a,b,c)=sin(a)b2+eca
b
c
np.meshgrid()
A
B
C
F = np.sin(A) * B**2 + np.exp(C)