Reihan_amn - 1 year ago 118

Python Question

I have a 2d numpy array and I need to add one column before the first column as id.

my array is this

`x = [['8' '4' 'M' '55' '7' 'S' '7' '2']`

['36' '4' 'F' '58' '1' 'M' '7' '7']

['33' '3' 'M' '34' '4' 'M' '2' '3']

['43' '1' 'F' '64' '4' 'M' '7' '68']

['1' '2' 'M' '87' '4' 'M' '7' '1']]

And the column that I want to add is this y = ['1' '2' '3' '4' '5']

Is there any way that I can do it? (I can find a solution for inserting row, but now column)

`target z = [['1' '8' '4' 'M' '55' '7' 'S' '7' '2']`

['2' '36' '4' 'F' '58' '1' 'M' '7' '7']

['3' '33' '3' 'M' '34' '4' 'M' '2' '3']

['4' '43' '1' 'F' '64' '4' 'M' '7' '68']

['5' '1' '2' 'M' '87' '4' 'M' '7' '1']]

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

define your new column:

```
col = np.array(['1','2','3','4','5'])
col.shape = (5,1)
```

and insert it at the start:

```
target = np.hstack((col, x))
```

for inserting at any given position `i`

, you can do it like this:

```
target = np.hstack((x[:,:i], col, x[:,i:]))
```

But it looks to me like using a pandas dataframe rather than a numpy array would be a better option...

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**