0

Let's consider the following numpy ndarray,

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

I want to make it to two column like,

    A     B
0   1     0
1   1     0
2   1     0
3   1     0
4   1     0
5   0     1
6   1     0

Now, I'm doing in the following way,

a = []
b = []
for i in lb_results:
    if i == 0:
        a.append(1)
        b.append(0)
    else:
        a.append(0)
        b.append(1)

lb_results = np.column_stack((a, b))
print(lb_results)

but I'm expecting something more optimized way, (less number of code lines are better, without using much more loops) Any suggestions would be grateful, Thanks.

2
  • There's no need for any loops, just create a second 1D array using the methods here and then stack (all you're doing is flipping 0's and 1's) Commented Oct 18, 2018 at 14:27
  • @roganjosh Thanks, It's also working fine. Commented Oct 18, 2018 at 15:44

1 Answer 1

1

You could use xor like so:

>>> c = (np.c_[:7] == 5).astype(int)
>>> c
array([[0],
       [0],
       [0],
       [0],
       [0],
       [1],
       [0]])
>>> c ^ (1, 0)
array([[1, 0],
       [1, 0],
       [1, 0],
       [1, 0],
       [1, 0],
       [0, 1],
       [1, 0]])

I guess this is about as short as it gets ;-)

The magic behind this is numpy broadcasting. Briefly, xor operator ^ gets applied to each pair between an element of the column c and an element of the the 1D sequence (1, 0) leading to the full "xor table" between the two.

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

4 Comments

Maybe unnecessarily short... I would suggest np.column_stack((np.logical_not(b), b))
@paul Thanks, I think, it would be difficult, if once we don't know the index of 1's (i.e, in your example it is '5')
@JaiK It works for any column c consisting of ones and zeros. The first line is just a shortcut to recreate your example vector. Please try it out: create a different c and do c ^ (1, 0).
@PaulPanzer Yes, Paul. Good, Working nice.. sorry, I understood mistakenly.

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.