我尝试使用np.insert
在给定索引处的数组中插入特定值。在我使用Numpy 1.12之前,代码运行正常但是使用新的Numpy 1.13.3时出现以下错误
ValueError: shape mismatch: value array of shape () could not be broadcast to indexing result of shape ()
我的代码:
intial_array= 1D numpy array
indices= 1D numpy array
values_to_insert= 1D numpy array
mt_new2=np.insert(intial_array, indices,values_to_insert)
此问题是否已知或有人知道如何解决此问题?
答案 0 :(得分:0)
早期numpy
可以根据需要复制values
以符合索引大小:
>>> x = numpy.arange(10)
>>> numpy.insert(x,[1,3,4,5],[10,20])
array([ 0, 10, 1, 2, 20, 3, 10, 4, 20, 5, 6, 7, 8, 9])
>>> numpy.__version__
'1.12.0'
New numpy期望匹配尺寸:
In [81]: x = np.arange(10)
In [82]: np.insert(x, [1,3,4,5],[10,20])
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-82-382864de5db0> in <module>()
----> 1 np.insert(x, [1,3,4,5],[10,20])
/usr/local/lib/python3.5/dist-packages/numpy/lib/function_base.py in insert(arr, obj, values, axis)
5085 slobj[axis] = indices
5086 slobj2[axis] = old_mask
-> 5087 new[slobj] = values
5088 new[slobj2] = arr
5089
ValueError: shape mismatch: value array of shape (2,) could not be broadcast to indexing result of shape (4,)
In [83]: np.insert(x, [1,3,4,5],[10,20,10,20])
Out[83]: array([ 0, 10, 1, 2, 20, 3, 10, 4, 20, 5, 6, 7, 8, 9])
看起来早期版本明确或隐含地使用resize
In [85]: np.insert(x, [1,3,4,5],np.resize([10,20,30],4))
Out[85]: array([ 0, 10, 1, 2, 20, 3, 30, 4, 10, 5, 6, 7, 8, 9])