0

I have a numpy array:

X = np.array([[1,0,1],
              [1,1,1],
              [0,1,0],
              [1,0,1]])

which has a shape of (4,3)

I would like to change this shape into (4,4) by adding 1 to the second dimension of the array, via:

X_b = np.ones((X.shape+(0,1)))

but what I get is:

ValueError: could not broadcast input array from shape (4,3) into shape (4,2,0,1)

What is the right way to do it?

Basically I want X_b to have a shape of (4,4) if X.shape = (4,3)

1 Answer 1

1

To fix your code, do this instead:

X_b = np.ones(X.shape + np.array((0,1)))

The catch here is that X.shape returns a plain Python tuple. By adding (0,1) you were actually performing tuple concatenation, instead of pairwise addition like you intended.

Of course, you could also just stick an extra column on to your existing array with append:

X_b = np.append(X, [[1]]*X.shape[0], axis=1)
Sign up to request clarification or add additional context in comments.

8 Comments

X_b[:,:-1] = X and then use X_b as input... probably doing the same thing. your answer looks good. Just waiting the minutes
@oakca assuming X_b was created with np.ones, then yep. The one "gotcha" is that X_b will be of dtype float64, which is the default for np.ones. Thus the dtypes of X and X_b may not match (eg if X.dtype==int)
Or np.hstack((X, np.ones((4,1), dtype=np.int))), which I find easier to visualize.
@xnx There's a whole bunch of these array-growing functions, and they're all roughly equivalent. Ideally you use none of them and instead just preallocate all your arrays (whose size you magically know in advance). Internally, both append and hstack are thin (5-10 lines) wrappers around concatenate.
Here you can find more about the thema stackoverflow.com/questions/8486294/…
|

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.