总体思路:我想在给定
f(x,y)
处获取两个变量 x = some value
的函数的 3D 曲面图的切片。问题是,例如,我必须知道在使用 x
创建 x
作为向量后 np.linspace
假定该值的索引。由于 SO 中的另一篇文章,找到这个索引是可行的。我不能做的是使用这个索引作为返回到不同向量的子集Z
,因为索引作为 1 元素列表(或元组)返回,并且我需要一个整数。当我使用 int()
时,我收到警告:
import numpy as np
lim = 10
x = np.linspace(-lim,lim,2000)
y = np.linspace(-lim,lim,2000)
X, Y = np.meshgrid(x, y)
Z = X**2 + Y**2
def find_nearest(array, value):
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return array[idx]
idx = int(np.where(x == find_nearest(x,0))[0])
print(idx)
print(Z[idx,:].shape)
Z
的最终子设置的形状是(2000,)
,这使我可以根据x
绘制它。
但是,如果我只是用
[0]
提取 np.where()
返回的值,则最终子集 Z
的形状(即 (1,2000)
)将不允许我将其与 x
进行绘制:
idx1 = np.where(x == find_nearest(x,0))[0]
print(idx1)
print(Z[idx1,:].shape)
如何提取与
x
is Want 的值对应的索引作为整数,从而避免警告?
分解从
np.where
得到的结果值:
>>> np.where(x == find_nearest(x,0))
(array([1000]),)
然后取消引用第一个元素:
>>> np.where(x == find_nearest(x,0))[0]
array([1000])
好吧,同样的事情。获取第一个元素:
>>> np.where(x == find_nearest(x,0))[0][0]
1000