Bishwajit Purkaystha - 12 days ago 5

Python Question

I have a numpy array:

`array([[1, 2, 3],`

[4, 5, 6],

[7, 8, 9]])

Now I want to add a column of all ones in front of it to get:

`array([[1, 1, 2, 3],`

[1, 4, 5, 6],

[1, 7, 8, 9]])

I saw many posts pertaining to my question, but none of them could solve my problem. I tried

`np.concatenate`

`np.append`

`np.hstack`

Answer

Simply use `np.concatenate`

:

```
>>> import numpy as np
>>> arr = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> np.concatenate((np.array([0,0,0])[:, np.newaxis], arr), axis=1)
array([[0, 1, 2, 3],
[0, 4, 5, 6],
[0, 7, 8, 9]])
```

But `hstack`

works too:

```
>>> np.hstack((np.array([0,0,0])[:, np.newaxis], arr))
array([[0, 1, 2, 3],
[0, 4, 5, 6],
[0, 7, 8, 9]])
```

The only "tricky" part is that both arrays must have the same number of dimensions, that's why I added the `[:, np.newaxis]`

- which adds a new dimension.

How to change the zeros to ones is left as an (easy) exercise :-)

If you want to prepend a 2D array you have to drop the `[:, np.newaxis]`

part:

```
np.concatenate((np.zeros((3,3), dtype=int), arr), axis=1)
array([[0, 0, 0, 1, 2, 3],
[0, 0, 0, 4, 5, 6],
[0, 0, 0, 7, 8, 9]])
```