w3resource

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


Place elements randomly in a 2D array.

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).

For more Practice: Solve these Related Problems:

  • Write a NumPy program to randomly assign a specified value to a fixed number of positions in a 2D array using np.random.choice.
  • Create a function that replaces randomly selected elements in a matrix with a given number and then returns the modified array.
  • Implement a solution that generates random row and column indices to insert a specified value at those locations.
  • Test the random placement function on arrays with different sizes and verify that the number of replacements matches the input parameter.

Go to:


PREV : Check if dimensions of two arrays match.
NEXT : Subtract mean of each row from a matrix.


Python-Numpy Code Editor:

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

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.