4

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.

3
  • concatenate is your friend here. Read its docs Commented Jan 16, 2021 at 1:32
  • Would this work? np.hstack([dat, np.linspace(1, dat.shape[0], dat.shape[0]).reshape((-1, 1))]) Commented Jan 16, 2021 at 1:36
  • 2
    np.c_[dat,1:len(dat)+1] Commented Jan 16, 2021 at 1:54

3 Answers 3

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Since np.append is misused so often, I prefer to see dat = np.concatenate([dat, a], 1) used instead (or of course the hstack).
1

Use numpy.column_stack:

newdat = np.column_stack([dat, range(1,dat.shape[0] + 1)])
print(newdat)
#[[0 1 0 1]
# [1 0 0 2]
# [0 0 1 3]]

Comments

0

Try something like this using numpy.insert():

import numpy as np

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

dat = np.insert(dat, 3, values=[range(1, 4)], axis=1)

print(dat)

Output:

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

More generally, you can make use of numpy.ndarray.shape for the appropriate sizing:

dat = np.insert(dat, dat.shape[1], values=[range(1, dat.shape[0] + 1)], axis=1)

Comments

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.