4

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)

1 Answer 1

10

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

Sign up to request clarification or add additional context in comments.

1 Comment

Also, np.concatenate((col, x), axis = 1)

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.