Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a column at specific location in 2D array in numpy?

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']]

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

And the target output is:

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']]

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

like image 464
Reihan_amn Avatar asked Mar 10 '23 13:03

Reihan_amn


1 Answers

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...

like image 131
Julien Avatar answered Mar 23 '23 06:03

Julien