python numpy 转换问题
我正在尝试使用以下代码进行插值
self.indeces = np.arange( tmp_idx[len(tmp_idx) -1] )
self.samples = np.interp(self.indeces, tmp_idx, tmp_s)
,其中 tmp_idx 和 tmp_s 是 numpy 数组。我收到以下错误:
数组无法安全地转换为 所需类型
你知道如何解决这个问题吗?
更新:
class myClass
def myfunction(self, in_array, in_indeces = None):
if(in_indeces is None):
self.indeces = np.arange(len(in_array))
else:
self.indeces = in_indeces
# clean data
tmp_s = np.array; tmp_idx = np.array;
for i in range(len(in_indeces)):
if( math.isnan(in_array[i]) == False and in_array[i] != float('Inf') ):
tmp_s = np.append(tmp_s, in_array[i])
tmp_idx = np.append(tmp_idx, in_indeces[i])
self.indeces = np.arange( tmp_idx[len(tmp_idx) -1] )
self.samples = np.interp(self.indeces, tmp_idx, tmp_s)
I'm trying to interpolate with the following code
self.indeces = np.arange( tmp_idx[len(tmp_idx) -1] )
self.samples = np.interp(self.indeces, tmp_idx, tmp_s)
where tmp_idx and tmp_s are numpy arrays. I get the following error:
array cannot be safely cast to
required type
Do you know how to fix this?
UPDATE:
class myClass
def myfunction(self, in_array, in_indeces = None):
if(in_indeces is None):
self.indeces = np.arange(len(in_array))
else:
self.indeces = in_indeces
# clean data
tmp_s = np.array; tmp_idx = np.array;
for i in range(len(in_indeces)):
if( math.isnan(in_array[i]) == False and in_array[i] != float('Inf') ):
tmp_s = np.append(tmp_s, in_array[i])
tmp_idx = np.append(tmp_idx, in_indeces[i])
self.indeces = np.arange( tmp_idx[len(tmp_idx) -1] )
self.samples = np.interp(self.indeces, tmp_idx, tmp_s)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
可能的问题之一是,当您有以下行时:
您正在将
tmp_s
和tmp_idx
设置为内置函数 np.array。然后,当您追加时,您将拥有对象类型数组,而np.interp
不知道如何处理。我认为您可能认为您正在创建零长度的空数组,但这不是 numpy 或 python 的工作原理。请尝试类似以下内容:
不能保证这会完美工作,因为我不知道您的输入或所需的输出,但这应该可以帮助您开始。请注意,在 numpy 中,如果有一种方法可以对整个数组执行所需的操作,通常不鼓励您循环遍历数组元素并一次对它们进行操作。使用内置的 numpy 方法总是要快得多。一定要查看 numpy 文档以了解可用的方法。您不应该像对待常规 Python 列表一样对待 numpy 数组。
One of your possible issues is that when you have the following line:
You are setting
tmp_s
andtmp_idx
to the built-in function np.array. Then when you append, you have have object type arrays, whichnp.interp
has no idea how to deal with. I think you probably thought that you were creating empty arrays of zero length, but that isn't how numpy or python works.Try something like the following instead:
No guarantees that this will work perfectly, since I don't know your inputs or desired outputs, but this should get you started. As a note, in numpy, you are generally discouraged from looping through array elements and operating on them one at a time, if there is a method that performs the desired operation on the entire array. Using built-in numpy methods are always much faster. Definitely look through the numpy docs to see what methods are available. You shouldn't treat numpy arrays the same way you would treat a regular python list.