Home > database >  replacing values with zeros
replacing values with zeros

Time:06-25

I have a numpy array, I want to replace whole values to zeros except some range of index.

1
2
3
4
5

I tried

Import numpy as np
data=np.loadtxt('data.txt')
print(data)

expected output

0
0
3
0
0

CodePudding user response:

You can traverse the array with a for loop and check if the traversed element is in a list of desired selected values:

import numpy as np

a = np.array([1, 2, 3, 4, 5])
nums = [3]

for i in range(len(a)):
    if a[i] in nums:
        pass
    else:
        a[i] = 0
print(a)

Output:

[0 0 3 0 0]

CodePudding user response:

As you're working with a numpy array, use vectorial methods.

Here isin to form a boolean mask for replacement:

data = np.array([1, 2, 3, 4, 5])
l = [3]

data[~np.isin(data, l)] = 0

data
# array([0, 0, 3, 0, 0])
  • Related