我创建了两个numpy数组。我想创建第三个数组作为这两个数组中每个元素的函数。我尝试了以下方法,但它不起作用。
X = np.arange(-180., 180., 1.)
Y = X
X, Y = np.meshgrid(X, Y)
Z = np.ndarray([func(x, y) for (x, y) in zip(X, Y)])
我收到以下错误:
ValueError: operands could not be broadcast together with shapes (2,360) (2,)
如果它与解决方案相关,这三个数组的目的是在matplotlib中构建一个3D图:
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
答案 0 :(得分:2)
为什么使用ndarray代替Z
,而不是(360,360)np.array
?
替换此行
Z = np.ndarray([func(x, y) for (x, y) in zip(X, Y)])
带
Z = np.array([func(x, y) for (x, y) in zip(X, Y)])
查看np.array()
和np.ndarray()
t1 = np.ndarray([0, 1, 2, 3, 4])
t1.shape
Out[39]: (0, 1, 2, 3, 4)
t2 = np.array([0, 1, 2, 3, 4])
t2.shape
Out[41]: (5,)