w3resource

NumPy: Repeat all the elements three times of a given array of string


Write a NumPy program to repeat all the elements three times of a given array of string.

Sample Solution:

Python Code:

# Importing the necessary library
import numpy as np

# Creating a NumPy array containing strings
x1 = np.array(['Python', 'PHP', 'Java', 'C++'], dtype=np.str)

# Displaying the original array
print("Original Array:")
print(x1)

# Using np.char.multiply to repeat each string element in x1 three times
new_array = np.char.multiply(x1, 3)

# Displaying the new array with each string element repeated three times
print("New array:")
print(new_array) 

Sample Input:

(['Python', 'PHP', 'Java', 'C++'], dtype=np.str)

Sample Output:

Original Array:
['Python' 'PHP' 'Java' 'C++']
New array:
['PythonPythonPython' 'PHPPHPPHP' 'JavaJavaJava' 'C++C++C++']

Explanation:

In the above exercise –

x1 = np.array(['Python', 'PHP', 'Java', 'C++'], dtype=np.str): This line creates a 1-dimensional numpy array x1 with 4 elements of string data type. The elements are 'Python', 'PHP', 'Java', and 'C++'.

new_array = np.char.multiply(x1, 3): This line applies the np.char.multiply() function to the x1 array with a value of 3. The np.char.multiply() function is used to replicate the elements of the input array. In this case, each string element of x1 is repeated 3 times, and the resulting new array is stored in the variable new_array.

Finally print() function print the content of new_array and output will be - ['PythonPythonPython' 'PHPPHPPHP' 'JavaJavaJava' 'C++C++C++']

Pictorial Presentation:

NumPy String: Repeat all the elements three times of a given array of string

Python-Numpy Code Editor: