1

Having an original numpy array like:

a = np.array([
    [12, 43],
    [42, 23],
    [33, 22],
    [53, 15],
    [34, 31]
])

I want to add a new column to a based on an array of indices:

indices = np.array([2, 3])

such that a becomes:

# if index is in "indices", new value is 1, otherwise 0

a = np.array([
    [12, 43, 0],
    [42, 23, 0],
    [33, 22, 1],
    [53, 15, 1],
    [34, 31, 0]
])

Note: I cannot use Pandas in this context, it has to be a pure numpy solution

1 Answer 1

1

Create a new nx1 zeros array and assign indices location to 1 and column_stack

b = np.zeros((a.shape[0],1))
b[indices] = 1
c = np.column_stack([a, b])

Out[28]:
array([[12., 43.,  0.],
       [42., 23.,  0.],
       [33., 22.,  1.],
       [53., 15.,  1.],
       [34., 31.,  0.]])
Sign up to request clarification or add additional context in comments.

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.