'Expand 2-D Numpy integer Array as binary but in parallel
I want to convert arrays of integers to 0 or 1s, padding with 0s if the other array possesses the larger value.
Examples:
ex1 = np.array([[0],[3]])
=> array([[0,0,0],[1,1,1]])
ex2 = np.array([[2,1],[0,0]])
=> array([[1,1,1],[0,0,0]])
ex3 = np.array([ [2,1,2],[3,1,1] ])
=> array([[1,1,0,1,1,1]
[1,1,1,1,1,0]])
How shall I achieve this? Can it also expand the N-dimension array?
Solution 1:[1]
Came up with this approach:
def expand_multi_bin(a):
# Create result array
n = np.max(a, axis=0).sum()
d = a.shape[0]
newa = np.zeros(d*n).reshape(d,n)
row=0
for x in np.nditer(a, flags=['external_loop'], order='F'):
# Iterate each column
for idx,c in enumerate(np.nditer(x)):
# Store it to the result array
newa[idx,row:row+c] = np.ones(c)
row += np.max(x)
return newa
Though, given the multiple loops, highly skeptical that this is the best approach.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shun |
