Could someone tell me how to change the array values randomly with Numpy?
For example, if there is a 5x5 array, I would like to write a program that makes 10 random values out of 25 elements zero.
Could someone please tell me?Thank you for your cooperation.
Simply generate 10 non-overlapping Index values in random numbers such as numpy.random.choice()
and so on.
In numpy.put()
, the element corresponding to that Index value should be zero.
import numpy as np
# Generate 5x5 arrays
arr=np.range(1,26).reshape(5,5)
# Generate 10 random values (no duplication)
p=np.random.choice(25,10,replace=False)
# Change the element equivalent to Index above to 0
np.put(arr,p,0)
print(arr)
#[[ 0 2 0 4 0]
# [ 6 7 8 0 0]
# [ 0 0 13 14 0]
# [16 17 18 0 20]
# [21 22 23 24 0]]
https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.choice.html
https://docs.scipy.org/doc/numpy/reference/generated/numpy.put.html
© 2024 OneMinuteCode. All rights reserved.