Reputation: 326
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]]
Upvotes: 0
Views: 878
Reputation: 341
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]]
Upvotes: 2
Reputation: 19957
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]])
Upvotes: 0