Repeat all the elements of a NumPy array of strings

Let us see how to repeat all elements of the given array of string 3 times.

Example :

Input : [‘Akash’, ‘Rohit’, ‘Ayush’, ‘Dhruv’, ‘Radhika’]
Output : [‘AkashAkashAkash’, ‘RohitRohitRohit’, ‘AyushAyushAyush’, ‘DhruvDhruvDhruv’, ‘RadhikaRadhikaRadhika’]

We will be using the numpy.char.multiply(a, i) method for this task.

numpy.char.multiply(a, i)

Syntax : numpy.char.multiply(a, i)
Parameters :



  • a : array of str or unicode
  • i : number of times to be repeated

Returns : Array of strings

Example 1 : Repeating 3 times.

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing the module
import numpy as np
  
# created array of strings
arr = np.array(['Akash', 'Rohit', 'Ayush'
                'Dhruv', 'Radhika'], dtype = np.str)
print("Original Array :")
print(arr)
  
# with the help of np.char.multiply()
# repeating the characters 3 times
new_array = np.char.multiply(arr, 3)
print("\nNew array :")
print(new_array)

chevron_right


Output :

Original Array :
[‘Akash’ ‘Rohit’ ‘Ayush’ ‘Dhruv’ ‘Radhika’]

New array :
[‘AkashAkashAkash’ ‘RohitRohitRohit’ ‘AyushAyushAyush’ ‘DhruvDhruvDhruv’ ‘RadhikaRadhikaRadhika’]

Example 2: Repeating 2 times.

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing the module
import numpy as np
  
# created array of strings
arr = np.array(['Geeks', 'for', 'Geeks'])
print("Original Array :")
print(arr)
  
# with the help of np.char.multiply()
# repeating the characters 3 times
new_array = np.char.multiply(arr, 2)
print("\nNew array :")
print(new_array)

chevron_right


Output :

Original Array :
['Geeks' 'for' 'Geeks']

New array :
['GeeksGeeks' 'forfor' 'GeeksGeeks']

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.