python numpy强制转换问题
我试图用下面的代码进行插值python numpy强制转换问题,python,casting,numpy,interpolation,Python,Casting,Numpy,Interpolation,我试图用下面的代码进行插值 self.indeces = np.arange( tmp_idx[len(tmp_idx) -1] ) self.samples = np.interp(self.indeces, tmp_idx, tmp_s) 其中,tmp_idx和tmp_是numpy阵列。我得到以下错误: 无法将数组安全地强制转换到 必需类型 你知道怎么解决这个问题吗 更新: class myClass def myfunction(self, in_array
self.indeces = np.arange( tmp_idx[len(tmp_idx) -1] )
self.samples = np.interp(self.indeces, tmp_idx, tmp_s)
其中,tmp_idx和tmp_是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)
您可能遇到的问题之一是,当您有以下行时:
tmp_s = np.array; tmp_idx = np.array;
您正在将tmp_s
和tmp_idx
设置为内置函数np.array。然后当你追加时,你有对象类型数组,它np。interp
不知道如何处理。我认为您可能认为您正在创建零长度的空数组,但numpy或python不是这样工作的
请尝试以下方法:
class myClass
def myfunction(self, in_array, in_indeces = None):
if(in_indeces is None):
self.indeces = np.arange(len(in_array))
# NOTE: Use in_array.size or in_array.shape[0], etc instead of len()
else:
self.indeces = in_indeces
# clean data
# set ii to the indices of in_array that are neither nan or inf
ii = ~np.isnan(in_array) & ~np.isinf(in_array)
# assuming in_indeces and in_array are the same shape
tmp_s = in_array[ii]
tmp_idx = in_indeces[ii]
self.indeces = np.arange(tmp_idx.size)
self.samples = np.interp(self.indeces, tmp_idx, tmp_s)
由于我不知道您的输入或期望的输出,因此不能保证这会完美地工作,但这应该让您开始。需要注意的是,在numpy中,如果有一种方法可以对整个数组执行所需的操作,则通常不鼓励您循环遍历数组元素并一次对它们进行操作。使用内置的numpy方法总是要快得多。一定要查看numpy文档,看看有哪些方法可用。您不应该像对待常规python列表那样对待numpy数组。对我很有用。什么类型的
tmp\u idx
和tmp\u s
?您能提供一个输出错误的更完整示例吗?请向我们展示self.indeces.dtype
、tmp\u idx.dtype
和tmp\u s.dtype
。它们是int64对象。我要更新上面的代码,它似乎在工作。。。是否可以强制numpy数组具有某些特定的数据,例如float或double?@Banana,array.astype(type)将返回数组的转换副本。通常,在创建数组时,最好确保数组的类型正确。