Skip to main content
 首页 » 编程设计

python之在 Numpy 中插入行和列

2025年05月04日15mengfanrong

我有以下代码

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 

我希望该函数执行的操作是给定一个大小为 i,j 的数组,它在每行和每列之间插入一个零行和一列。

所以如果我有

`array([[1,2,3],  
        [4,5,6], 
        [7,8,9]])` 

该函数将返回结果

[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