How to replace values in numpy array at the same time

We Are Going To Discuss About How to replace values in numpy array at the same time . So lets Start this Python Article.

How to replace values in numpy array at the same time

  1. How to solve How to replace values in numpy array at the same time

    It's better to use np.select if you've multiple conditions:
    a = np.array([7, 1, 2, 0, 2, 3, 4, 0, 5]) a = np.select([a == 7, a == 2], [2, 3], a)
    OUTPUT:
    [2 1 3 0 3 3 4 0 5]

  2. How to replace values in numpy array at the same time

    It's better to use np.select if you've multiple conditions:
    a = np.array([7, 1, 2, 0, 2, 3, 4, 0, 5]) a = np.select([a == 7, a == 2], [2, 3], a)
    OUTPUT:
    [2 1 3 0 3 3 4 0 5]

Solution 1

It’s better to use np.select if you’ve multiple conditions:

a = np.array([7, 1, 2, 0, 2, 3, 4, 0, 5])
a = np.select([a == 7, a == 2], [2, 3], a)

OUTPUT:

[2 1 3 0 3 3 4 0 5]

Original Author Nk03 Of This Content

Solution 2

Numpy provide the comparison to a scalar with the standard == operator, such that arr == v return a boolean array. Taking arr[arr == v] takes the subset (or slice) of arr where the condition is met so this snippet should work.

import numpy as np
arr = np.array([7, 1, 2, 0, 2, 3, 4, 0, 5])
arr[arr == 7] = 2
arr
array([2, 1, 2, 0, 2, 3, 4, 0, 5])

Original Author Maxime A Of This Content

Conclusion

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

ittutorial team

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment