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.

Jai K
  • 375
  • 1
  • 4
  • 12
  • There's no need for any loops, just create a second 1D array using the methods [here](https://stackoverflow.com/questions/26890477/flipping-zeroes-and-ones-in-one-dimensional-numpy-array) and then stack (all you're doing is flipping 0's and 1's) – roganjosh Oct 18 '18 at 14:27
  • @roganjosh Thanks, It's also working fine. – Jai K Oct 18 '18 at 15:44

1 Answers1

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.

Paul Panzer
  • 51,835
  • 3
  • 54
  • 99
  • Maybe unnecessarily short... I would suggest `np.column_stack((np.logical_not(b), b))` – Markus Oct 18 '18 at 15:04
  • @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') – Jai K Oct 18 '18 at 15:34
  • @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)`. – Paul Panzer Oct 18 '18 at 15:48
  • 1
    @PaulPanzer Yes, Paul. Good, Working nice.. sorry, I understood mistakenly. – Jai K Oct 18 '18 at 15:56