我试图用np.where()在x_norm数组中查找元素的索引,但效果不佳。有没有办法找到元素的索引?
x_norm = np.linspace(-10,10,1000)
np.where(x_norm == -0.19019019)Np.where与np.arange()一起工作,可以找到由linspace创建的数组的第一个或最后一个元素的索引。
发布于 2020-12-31 05:25:23
与粘贴到np.where的数字(-0.19019019019019012)相比,np.linspace生成的数字包含的小数位数更多。
因此,使用np.argmin查找最接近的值并避免舍入误差可能更好:
x_norm = np.linspace(-10,10,1000)
yournumber=-0.19019019
idx=np.argmin(np.abs(x_norm-yournumber))然后,您可以更进一步,将np.where(x_norm==x_norm[idx])添加到您的代码中,以防您的数组具有重复项。
发布于 2021-02-11 20:52:02
使用np.round将精度级别设置为8,然后使用np.where过滤数据作为掩码,然后将掩码应用于数组。
x_norm = np.round(np.asarray(np.linspace(-10,10,1000)),8)
results=x_norm[np.where(x_norm==-9.91991992)]
print(results)https://stackoverflow.com/questions/65513536
复制相似问题