0

I want to append a second column to an ndarray, containing the opposite binary value.

Take this ndarray of n rows and 1 column, containing binary values:

[[0]
 [1]
 [0]
 [1]]

I want to have a for loop that yields this output:

[[0,1]
 [1,0]
 [0,1]
 [1,0]]

Accessing the nested ndarray, adding the opposite: either 1 or 0.

Note: append(), insert() etc. do not work as this is a multi-dimensional array. Not a list (hence many [])

2 Answers 2

2

Try this by taking a not gate operation on the binary values to change 0 to 1 and vice versa. Then you can horizontally stack the 2 arrays a and not a into a (4,2) array -

import numpy as np

a = np.array([[0],[1],[0],[1]])
b = np.logical_not(a).astype(int)

np.hstack([a,b])
array([[0, 1],
       [1, 0],
       [0, 1],
       [1, 0]])
Sign up to request clarification or add additional context in comments.

2 Comments

Genius! Thank you. You did it so fast like it was nothing haha
Thanks, Quang Hoang did it faster than me :). Do check his approaches as well. They would help you explore how NumPy works as well (broadcasting using 1-a for example)
1

You can try:

np.concatenate([a,1-a], axis=1)

Or

np.hstack([a,1-a])

Output:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.