Reputation: 4709
I don't know the number of rows and columns of a 2d array (a
) I need in advance:
a = np.empty( (0,0), dtype=np.uint8 )
a.ndim
2
I managed to convert each line I read from a file to an 1d array of bytes called line
I want to add/append each line to a
, so I tried :
np.vstack( (a,line) )
but I get :
ValueError: all the input arrays must have same number of dimensions
And if I call a=np.append(a,line)
, the number of dimensions becomes 1
Can you help ?
Upvotes: 1
Views: 2765
Reputation: 402263
You're on the right track with np.vstack
. The only requirement is that the arrays being stacked must have the same number of columns. Take a look at this:
array = None # initialise array to None first
for ...: # now inside the loop
line = ... # read line from somewhere and get something like [201, 81, 237, 230]
if array is None:
array = line
else:
array = np.vstack((array, line))
In terms of performance, this is actually a little more wasteful than just creating an array at the end out of a list. This is the problem with numpy arrays - they're immutable in terms of dimensions.
Upvotes: 2
Reputation: 2086
Numpy arrays cannot be appended to. The easiest way for you to do what you are trying to achieve would be to use a list and call np.asarray()
on it.
a = []
# Build list from file
a = np.asarray(a)
Upvotes: 1