w3resource

NumPy: Repeat elements of an array


Repeat Each Array Element

Write a NumPy program to repeat array elements.

Pictorial Presentation:

Python NumPy: Repeat elements of an array

Sample Solution:

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Repeating the value 3, four times and creating a NumPy array
x = np.repeat(3, 4)
print(x)

# Creating a NumPy array
x = np.array([[1, 2], [3, 4]])

# Repeating each element in the array twice
print(np.repeat(x, 2))

Sample Output:

[3 3 3 3]                                                              
[1 1 2 2 3 3 4 4]

Explanation:

In the above code -

x = np.repeat(3, 4): The np.repeat function repeats the value 3 four times, creating a new NumPy array: [3, 3, 3, 3].

x = np.array([[1, 2], [3, 4]]): A 2x2 NumPy array x is created with elements [1, 2] in the first row and [3, 4] in the second row.

print(np.repeat(x, 2)): The np.repeat function is called again, this time with the 2D NumPy array x. By default, the elements in the input array are flattened, and then each element is repeated twice. The resulting 1D array is [1, 1, 2, 2, 3, 3, 4, 4].

The final output is printed: [1, 1, 2, 2, 3, 3, 4, 4].


For more Practice: Solve these Related Problems:

  • Use np.repeat to duplicate each element of an array a specified number of times and check the new length.
  • Create a function that repeats each element in an array and then reshapes the output into a desired format.
  • Repeat elements in a 2D array along a specific axis and verify the result by comparing slices.
  • Apply np.repeat on an array of strings or numbers and ensure that the order of elements is maintained.

Python-Numpy Code Editor:

Previous: Write a NumPy program to construct an array by repeating.
Next: Write a NumPy program to find the indices of the maximum and minimum values along the given axis of an array.

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.