w3resource

NumPy: Place a specified element in specified time randomly in a specified 2D array

NumPy: Array Object Exercise-181 with Solution

Write a NumPy program to place a specified element in specified time randomly in a specified 2D array.

Pictorial Presentation:

Python NumPy: Place a specified element in specified time randomly in a specified 2D array

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Defining variables n (size of the square array), i (number of random elements), and e (specified element)
n = 4
i = 3
e = 10

# Creating an array of zeros with shape (n, n)
array_nums1 = np.zeros((n, n))

# Displaying the original array of zeros
print("Original array:")
print(array_nums1)

# Putting the specified element 'e' in 'i' randomly chosen positions within the array
np.put(array_nums1, np.random.choice(range(n * n), i, replace=False), e)

# Displaying the array after placing the specified element 'e' in 'i' randomly chosen positions
print("\nPlace a specified element in specified time randomly:")
print(array_nums1) 

Sample Output:

Original array:
[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]

Place a specified element in specified time randomly:
[[10.  0.  0.  0.]
 [10.  0.  0.  0.]
 [ 0.  0.  0. 10.]
 [ 0.  0.  0.  0.]]

Explanation:

In the above example -

Three variables 'n', 'i', and 'e' are assigned values 4, 3, and 10, respectively.

array_nums1 is initialized as a 2D NumPy array of zeros with shape (n, n), which in this case is (4, 4).

np.put(array_nums1, np.random.choice(range(n*n), i, replace=False), e):

In the above code -

  • np.random.choice is used to randomly choose 'i' unique elements from the range of 0 to (n * n) - 1, i.e., 0 to 15.
  • The parameter replace=False ensures that the elements are chosen without replacement, making them unique.
  • np.put is used to replace the chosen elements in the flattened version of array_nums1 with the value 'e' (10).

Python-Numpy Code Editor:

Previous: Write a NumPy program to check whether the dimensions of two given arrays are same or not.
Next: Write a NumPy program to subtract the mean of each row of a given matrix.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/python-numpy-exercise-181.php