NumPy: Repeat all the elements three times of a given array of string
NumPy String: Exercise-2 with Solution
Write a NumPy program to repeat all the elements three times of a given array of string.
Sample Solution:-
Python Code:
import numpy as np
x1 = np.array(['Python', 'PHP', 'Java', 'C++'], dtype=np.str)
print("Original Array:")
print(x1)
new_array = np.char.multiply(x1, 3)
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:
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a NumPy program to concatenate element-wise two arrays of string.
Next: Write a NumPy program to capitalize the first letter, lowercase, uppercase, swapcase, title-case of all the elements of a given array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Python: Tips of the Day
Memory Footprint Of An Object:
import sys x = 'farhadmalik' print(sys.getsizeof(x))
60
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook