Issue
Suppose there's an array
arr = np.array((0,0,1,2,0,1,2,2,1,0))
What I'd like to do is to randomly replace n
values with None
. What I tried is
n = 5
arr[[random.randint(0, len(arr)-1) for i in range(n)]] = None
but what I get is
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
How can I achieve that?
Solution
You'll first have to convert your array into float type and then you can replace random indices with np.nan
(as None
won't be supported by numpy):
n =5
arr = arr.astype(float)
idx = np.random.choice(len(arr),n ,replace=False)
np.put(arr, idx, [np.nan]*n)
print(arr)
Output:
[nan nan 1. nan 0. nan 2. 2. nan 0.]
Answered By - Suraj Shourie
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.