I have a 2D numpy array with size n * m, and I need to replace each value with 2 valus and result in an array with size n * 2m.
Replace pattern:1 with [1,0], 2 with [0,1] and 0 with [0,0]
Input: [[1,0,2],[2,2,1]]
Desired Output: [[1,0,0,0,0,1],[0,1,0,1,1,0]]
It can be easily done with a for loop, however I’m trying to find a ‘numpy’ way of doing it, to achieve maximum efficiency.
res = np.zeros((arr.shape[0],arr.shape[1]*2))
for index, row in enumerate(arr):
temp = np.array([])
for e in row:
if e == 1:
temp = np.append(temp,[1,0])
elif e == 2:
temp = np.append(temp,[0,1])
else:
temp = np.append(temp,[0,0])
res[index] = temp
>Solution :
As you have values 0, 1, 2, I would use a reference array to map the values by indexing:
a = np.array([[1,0,2],[2,2,1]])
mapper = np.array([[0, 0], # position 0
[1, 0], # position 1
[0, 1]]) # position 2
out = mapper[a].reshape((len(a), -1))
Output:
array([[1, 0, 0, 0, 0, 1],
[0, 1, 0, 1, 1, 0]])