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)

tel
  • 13,005
  • 2
  • 44
  • 62
oakca
  • 1,408
  • 1
  • 18
  • 40

1 Answers1

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)
tel
  • 13,005
  • 2
  • 44
  • 62
  • `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 Nov 21 '18 at 20:17
  • @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 `dtype`s of `X` and `X_b` may not match (eg if `X.dtype==int`) – tel Nov 21 '18 at 20:41
  • Or `np.hstack((X, np.ones((4,1), dtype=np.int)))`, which I find easier to visualize. – xnx Nov 21 '18 at 20:42
  • @xnx There's a [whole bunch of these array-growing functions](https://stackoverflow.com/q/8486294/425458), 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`](https://github.com/numpy/numpy/blob/v1.15.0/numpy/lib/function_base.py#L4476-L4528) and [`hstack`](https://github.com/numpy/numpy/blob/ccfbcc1cd9a4035a467f2e982a565ab27de25b6b/numpy/core/shape_base.py#L236-L288) are thin (5-10 lines) wrappers around `concatenate`. – tel Nov 21 '18 at 20:48
  • Here you can find more about the thema https://stackoverflow.com/questions/8486294/how-to-add-an-extra-column-to-a-numpy-array – oakca Nov 21 '18 at 21:03
  • `X.shape+np.array(0,1)` `*** TypeError: data type not understood` – oakca Nov 21 '18 at 21:51
  • @oakca I fixed the answer. Just had to add some parentheses (and remove some unneeded ones). – tel Nov 21 '18 at 21:56
  • still the same error. and sorry about that maybe old version let me check – oakca Nov 21 '18 at 21:57