I have two arrays mp
of shape (240, 480) and pop_fts_norm
which is an array of length N
of arrays of shape (240, 480). I want to create an array of length N
with values from mp
but only where elements of x
are != 0, for each array x
in pop_fts_norm.
Inefficient code:
full_mp = np.array([np.array([mp[i][j] if (x != 0)[i][j] is True else 0 for i in range(240) for j in range(480)]).reshape(240, 480) for x in pop_fts_norm], dtype='float32')
full_mp.shape
This works but works slowly.. How can be more efficiently written in pythonic style ?
Thanks, Petru
CodePudding user response:
full_mp = np.array([np.where(x != 0, mp, 0) for x in pop_fts_norm])
full_mp.shape
Found a solution.
CodePudding user response:
You can transform your matrices in the array to a set of 0 and 1, and after that you can just multiply elementwise the two matrix to get the result:
for x in pop_fts_norm:
x[x!=0] = 1
full_mp = np.array([np.array(np.multiply(mp,x) for x in pop_fts_norm])