如何在python中更改2D数组的列数?
在下面的代码片段中(编写此代码只是为了说明问题),我最初创建了一个大小为3*4的2D数组。现在,在执行代码的过程中,在某个时间步,我需要将第三行中的列数从4更改为2。我尝试了以下方法,但它显示了值错误。如何做到这一点?有人能描述一下吗如何在python中更改2D数组的列数?,python,Python,在下面的代码片段中(编写此代码只是为了说明问题),我最初创建了一个大小为3*4的2D数组。现在,在执行代码的过程中,在某个时间步,我需要将第三行中的列数从4更改为2。我尝试了以下方法,但它显示了值错误。如何做到这一点?有人能描述一下吗 import numpy as np A=np.ones((3,4)) # Some other portion of the code for i in range(0,3): if(i==2): # In the third row
import numpy as np
A=np.ones((3,4))
# Some other portion of the code
for i in range(0,3):
if(i==2): # In the third row
A[i,:]=np.ones(2) # Change the size of this third row.Now only need two elements (two 1's) in it
print(A)
ValueError: could not broadcast input array from shape (2) into shape (4)
因为Numpy只支持新行,所以新行的维度与列的输入相同(例如,4) 您可以从Numpy更改为list
import numpy as np
A=np.ones((3,4))
A = A.tolist()
for i in range(0,3):
if(i==2): # In the third row
A[i] = [1]*2
print(A)
不能更改结构化数据表的维度, 你可以试试:
A=np.ones((3,4))
row_no = 2
for i in range(0,row_no+1):
if(i==row_no):
A[i,:row_no]=np.ones(2)
A[i,row_no+1:]= np.nan #or 0 or somr other placeholder
print(A)