1

Say I have N numpy arrays, each of size (x, y, z), where y and z are the same for all but x differs for each. How would I combine these to a numpy array of size (w, y, z) where w is the sum of all x.

Or, for a numerical example: I have a list of 3 numpy array with sizes (14, 32, 32), (7, 32, 32), (50, 32, 32). How do I turn these into a (71, 32, 32) sized numpy array efficiently?

2 Answers 2

3

You can just concatenate them along the first axis. If your 3 numpy arrays are named x1, x2, and x3, your new array would be defined as x_combined = np.concatenate((x1,x2,x3),axis=0)

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

4 Comments

I have tried this already, but I get the error that the input arrays have to have the same dimensions. It may be the way my list of arrays is constructed, so I will double check that.
It was the data. I am working with images, and for some reason one set had not loaded so it had a shape of (0,).
If the other dimensions are the same, this method should work with no problem. For the axis you are concatenating along, the input arrays can have any length as long as the others are identical in length.
I removed that set of images (which for some reason does not load) and the issue was resolved. I had thought it was the way I was doing it as I had tried both of these suggestions already and they did not work because of that.
2

Try np.vstack

a, b , c = np.ones((14, 32, 32)), np.ones((7, 32, 32)), np.ones((50, 32, 32))

out = np.vstack([a,b,c])

In [119]: a.shape
Out[119]: (14, 32, 32)

In [120]: b.shape
Out[120]: (7, 32, 32)

In [121]: c.shape
Out[121]: (50, 32, 32)

In [122]: out.shape
Out[122]: (71, 32, 32)

3 Comments

I have tried this already, but I get the error that the input arrays have to have the same dimensions. It may be the way my list of arrays is constructed, so I will double check that.
double check with the shape command as in my answer. That error indicates one of your array doesn't match on both w, z dimension.
It was the data. I am working with images, and for some reason one set had not loaded so it had a shape of (0,).

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.