1

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 ?

8
  • 1
    Have you tried gathering all the 1d arrays into a list and calling np.array on it? Commented Jul 3, 2017 at 15:09
  • @Anis What do you mean by gathering and how do I do that ? Commented Jul 3, 2017 at 15:11
  • Where does line come from? It may be possible to simplify your solution. Commented Jul 3, 2017 at 15:13
  • @cᴏʟᴅsᴘᴇᴇᴅ line is an array of uint8, example : [201, 81, 237, 230] Commented Jul 3, 2017 at 15:15
  • And where do you get it from? Is it part of a bigger list? Or do you call it inside some function? Commented Jul 3, 2017 at 15:16

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@COLDSPEED You are absolutely right, I tried both solutions and the one from Tom Wyllie is both faster and simpler.
@SebMa Cheers. :)
@COLDSPEED Bye :-)
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.