Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace each element in a numpy array with multiple values?

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]]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading