0

Given two arrays as such

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

I want to create a numpy array based on conditions as

output = np.zeros(len(arr1))

for i in range(0, len(arr1)):
    if a[i] == 0 and b[i] == 0:
        output[i] = 0
    elif a[i] == 1 and b[i] == 0:
        output[i] = 1
    elif a[i] == 0 and b[i] == 1:
        output[i] = 2
    elif a[i] == 1 and b[i] == 1:
        output[i] = 3


expected_output = np.array([0,1,2,3])

what is the fastest way of creating such array?

6
  • edited. I hope it's clearer now. I have tried using np.where, but it doesn't seem to support different outputs from different conditions. Commented Jan 22, 2020 at 0:47
  • Err... Isn't this just counting upwards? This isn't very clear still. Commented Jan 22, 2020 at 0:54
  • 2
    c = a + 2*b should do it Commented Jan 22, 2020 at 0:56
  • edited with a simpler example Commented Jan 22, 2020 at 1:02
  • @hpaulj I wonder if c = a | b << 2 is faster? Commented Jan 22, 2020 at 1:05

3 Answers 3

1

The others gave examples how to do this in pure python. If you want to do this with arrays with 100.000 elements, you should use numpy:

In [1]: import numpy as np
In [2]: vector1 = np.array([0,1,0,1,0,1])
In [3]: vector2 = np.array([0,0,1,1,2,2])

Doing the element-wise addition is now as trivial as

In [4]: sum_vector = vector1 + vector2 * 2
In [5]: print(sum_vector) # python3.x kaugh...
[0, 1, 2, 3, 4, 5]

just like in Matlab ;-)

U may see also : Element-wise addition of 2 lists?

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

Comments

0

As answer above sugested, this is the fast\easiest way:

import numpy as np

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

a + 2*b

Comments

0

In the most generalized sense, you can use boolean arrays to assign values to indices matching whatever criteria that you want.

This:

for i in range(0, len(arr1)):
    if a[i] == 0 and b[i] == 0:
        output[i] = 0
    elif a[i] == 1 and b[i] == 0:
        output[i] = 1
    elif a[i] == 0 and b[i] == 1:
        output[i] = 2
    elif a[i] == 1 and b[i] == 1:
        output[i] = 3

Is equivalent to:

output[a == 0 & b == 0] = 0
output[a == 1 & b == 0] = 1
output[a == 0 & b == 1] = 2
output[a == 1 & b == 1] = 3

or:

a0 = a == 0
b0 = b == 0
a1 = a == 1
b1 = b == 1
output[a0 & b0] = 0
output[a1 & b0] = 1
output[a0 & b1] = 2
output[a1 & b1] = 3

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.