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:

import numpy as np
n = 4
i = 3
e = 10
array_nums1 = np.zeros((n,n))
print("Original array:")
print(array_nums1)
np.put(array_nums1, np.random.choice(range(n*n), i, replace=False), e)
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.]]

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

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 Python skills with w3resource's quiz



Python: Tips of the Day

List comprehension:

>>> m = [x ** 2 for x in range(5)]
>>> m
[0, 1, 4, 9, 16]