Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: adding index as new column to 2D array

Suppose I have np.array like below

dat = array([[ 0,  1,  0],
[ 1,  0,  0],
[0, 0, 1]]
)

What I want to do is that adding the (index of row + 1) as a new column to this array, which is like

newdat = array([[ 0,  1,  0, 1],
[ 1,  0,  0, 2],
[0, 0, 1, 3]]
)

How should I achieve this.

like image 952
Nicolas H Avatar asked Oct 28 '25 09:10

Nicolas H


1 Answers

You can also use np.append(). You can also get more info about [...,None] here

import numpy as np

dat = np.array([
    [0, 1, 0],
    [1, 0, 0],
    [0, 0, 1]
])

a = np.array(range(1,4))[...,None] #None keeps (n, 1) shape
dat = np.append(dat, a, 1)

print (dat)

The output of this will be:

[[0 1 0 1]
 [1 0 0 2]
 [0 0 1 3]]

Or you can use hstack()

a = np.array(range(1,4))[...,None] #None keeps (n, 1) shape
dat = np.hstack((dat, a))

And as hpaulj mentioned, np.concatenate is the way to go. You can read more about concatenate documentation. Also, see additional examples of concatenate on stackoverflow

dat = np.concatenate([dat, a], 1)
like image 142
Joe Ferndz Avatar answered Oct 29 '25 23:10

Joe Ferndz