Python 在Numpy中插入行和列

Python 在Numpy中插入行和列,python,numpy,Python,Numpy,我有以下代码 row, col = image.shape print image for x in range(row): for y in range(col): image = np.insert(image, [x,y], values=0, axis=1) print image 当我运行代码时,出现了这个错误 Traceback (most recent call last): File "C:\...\Code.py", line 55, in <modul

我有以下代码

row, col = image.shape
print image
for x in range(row):
  for y in range(col):
    image = np.insert(image, [x,y], values=0, axis=1)
print image
当我运行代码时,出现了这个错误

Traceback (most recent call last):
  File "C:\...\Code.py", line 55, in <module>
    expand(img1)
  File "C:\...\Code.py", line 36, in expand
    image = np.insert(image, [x,y], values=0, axis=1)
  File "C:\Python27\lib\site-packages\numpy\lib\function_base.py", line 3627, in insert
    new[slobj2] = arr
ValueError: array is not broadcastable to correct shape
该函数将返回

[1,0,2,0,3,0]
[0,0,0,0,0,0]
[4,0,5,0,6,0]
[0,0,0,0,0,0]
[7,0,8,0,9,0]
[0,0,0,0,0,0]
我也试过,

row, col = image.shape
for x in range(row):
  image = np.insert(image, x, values=0, axis=1)
for y in range(col):
  image = np.insert(image, y, values=0, axis=1)
但是我没有得到我想要的结果

避免使用insert和其他逐渐修改数组形状的函数-这些类型的函数在NumPy中通常非常缓慢。而是预先分配和填充:

newimage = np.zeros((row*2, col*2))
newimage[::2,::2] = image
避免使用insert和其他逐渐修改数组形状的函数-这些类型的函数在NumPy中通常非常慢。而是预先分配和填充:

newimage = np.zeros((row*2, col*2))
newimage[::2,::2] = image
np.insert用于指定多个插入点。检查它的帮助

image=np.arange(1,10).reshape(3,3)
image=np.insert(image,[1,2,3],0,0)
image=np.insert(image,[1,2,3],0,1)
产生

array([[1, 0, 2, 0, 3, 0],
       [0, 0, 0, 0, 0, 0],
       [4, 0, 5, 0, 6, 0],
       [0, 0, 0, 0, 0, 0],
       [7, 0, 8, 0, 9, 0],
       [0, 0, 0, 0, 0, 0]])
np.insert执行预分配和填充技巧,但更具通用性

在我的时间测试中,Neonneo的[::2,::2]插入方法要快很多—10-30倍。但这可能更难一概而论。np.insert的使用还不错——对于1000x1000阵列,我得到了300ms的时间

使用2个切片进行索引速度更快。使用np.ix的更通用的高级索引速度较慢,但仍比np.insert快2-3倍

np.insert用于指定多个插入点。检查它的帮助

image=np.arange(1,10).reshape(3,3)
image=np.insert(image,[1,2,3],0,0)
image=np.insert(image,[1,2,3],0,1)
产生

array([[1, 0, 2, 0, 3, 0],
       [0, 0, 0, 0, 0, 0],
       [4, 0, 5, 0, 6, 0],
       [0, 0, 0, 0, 0, 0],
       [7, 0, 8, 0, 9, 0],
       [0, 0, 0, 0, 0, 0]])
np.insert执行预分配和填充技巧,但更具通用性

在我的时间测试中,Neonneo的[::2,::2]插入方法要快很多—10-30倍。但这可能更难一概而论。np.insert的使用还不错——对于1000x1000阵列,我得到了300ms的时间

使用2个切片进行索引速度更快。使用np.ix的更通用的高级索引速度较慢,但仍比np.insert快2-3倍


您能否解释第二行中的语法是如何工作的?它使用NumPy的扩展切片表示法将每隔一行和每一列设置为图像中相应的值。您能否解释第二行中的语法是如何工作的?它使用NumPy的扩展切片将每隔一行和每一列设置为图像中相应的值表示法。使用高级索引,您可能会使预分配和填充方法通用化。使用高级索引,您可能会使预分配和填充方法通用化。