0

I have a numpy array with dimensions (1316, 21) and I need to increase it to (1329, 21). It doesn't matter what values are stored in the added space at the end. I tried to do:

    x = np.append(x, np.zeros(13))

But that changes the dimensions of the array to (27649,) which shows that it is converting it into a one dimensional array then adding the zeros to the end.

How do I append empty 2 dimensional values to an array like this?

mbohde
  • 109
  • 1
  • 7
  • 2
    Does this answer your question? [Good ways to "expand" a numpy ndarray?](https://stackoverflow.com/questions/12668027/good-ways-to-expand-a-numpy-ndarray) – Amin Guermazi Apr 11 '21 at 20:50

3 Answers3

2

Ummm...there is no converting the dimensions of a numpy array in python. A numpy array is simply a section of your RAM. You can't append to it in the sense of literally adding bytes to the end of the array, but you can create another array and copy over all the data (which is what np.append(), or np.vstack(), or np.concatenate(), etc.). In general, the dimensions of your array is simply a few variables that python keeps track of to present the data in the array to you, same thing as it's dtype.

For example,

 X = np.array([1,2,3,4,5],dtype='int32')
 print(X)
 X.dtype = 'int16' #The data is not converted it is simply displayed differently now. 
 print(X)          #Displays the data for the array. 
 X.shape = (5,2)   #Does not convert the data or touch it. 
 print(X)          #Displays the data for you using the parameter set in .shape. 

For your data, you can simply update the .shape when you append more data.

x = np.append(x, np.zeros((13,21)))
x.shape = (1329, 21)
Bobby Ocean
  • 3,120
  • 1
  • 8
  • 15
1

Use np.concatenate or np.vstack

np.concatenate([x, np.zeros((13, x.shape[1]))], axis=0)
# or
np.vstack([x, np.zeros((13, x.shape[1]))])
Gabriel A.
  • 609
  • 3
  • 7
0

May be like this:

import numpy as np

x = np.array([[1, 2, 3,4], [4, 5, 6,7]])
x = np.append(x, [np.zeros(4) for _ in range(13)] , axis=0)
print(x.shape)
print(x)