0

I have a list of values and a numpy bool array that looks like the following:

[[False  True  True False False  True]
 [ True  True  True False False  True]
 [ True  True  True  True  True  True]]



list = [1, 7, 2, 2, 3, 7, 1, 1, 4, 2, 9, 1, 2]

My goal is to add the integers in list to the True values in the bool array via column-wise, and if possible have the false values contain the integer 0. Please keep in mind that I am trying to iterate through the bool arrays column-wise, so the end result would look like:

 [[0  2  7  0  0  9]
 [ 1  2  1  0  0  1]
 [ 7  3  1  4  2  2]] 

2 Answers 2

2

Use transpose method:

import numpy as np
boo = np.array([[False, True, True, False, False, True],
                [True, True, True, False, False, True],
                [True, True, True, True, True, True]])
x = np.zeros(boo.shape, dtype=int)
y = np.array([1, 7, 2, 2, 3, 7, 1, 1, 4, 2, 9, 1, 2])
x.T[boo.T] = y
print(x)

[[0 2 7 0 0 9]
 [1 2 1 0 0 1]
 [7 3 1 4 2 2]]
Sign up to request clarification or add additional context in comments.

2 Comments

Using the transposed view! Nice.
This is exactly what I needed. For some reason I couldn't figure it out having to transpose two objects
0

Setup

a
Out[163]: 
array([[False,  True,  True, False, False,  True],
       [ True,  True,  True, False, False,  True],
       [ True,  True,  True,  True,  True,  True]], dtype=bool)

l
Out[164]: [1, 7, 2, 2, 3, 7, 1, 1, 4, 2, 9, 1, 2]

Solution

Use a list comprehension and pop function:
np.array([l.pop(0) if e else 0 for e in a.flatten('F')]).reshape(a.shape,order='F')
Out[177]: 
array([[0, 2, 7, 0, 0, 9],
       [1, 2, 1, 0, 0, 1],
       [7, 3, 1, 4, 2, 2]])

Another more verbose way to do this:

#flatten a to a 1D array of int type
a2 = a.flatten('F').astype(int)

#replace 1s with values from list
a2[a2==1] = l

#reshape a2 to the shape of a
a2.reshape(a.shape,order='F')
Out[162]: 
array([[0, 2, 7, 0, 0, 9],
       [1, 2, 1, 0, 0, 1],
       [7, 3, 1, 4, 2, 2]])

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.