NumPy: Split the element of a given array with spaces
Write a NumPy program to split the element of a given array with spaces.
Sample Solution:
Python Code:
# Importing necessary library
import numpy as np
# Creating a NumPy array containing a single string
x = np.array(['Python PHP Java C++'], dtype=np.str)
# Displaying the original array
print("Original Array:")
print(x)
# Splitting the single string in the array based on spaces
r = np.char.split(x)
# Displaying the result after splitting the string
print("\nSplit the element of the said array with spaces: ")
print(r)
Sample Input:
(['Python PHP Java C++'], dtype=np.str)
Sample Output:
Original Array: ['Python PHP Java C++'] Split the element of the said array with spaces: [list(['Python', 'PHP', 'Java', 'C++'])]
Explanation:
In the above exercise –
x = np.array(['Python PHP Java C++'], dtype=np.str): This code creates a 1-dimensional numpy array x of strings containing only one element "Python PHP Java C++".
r = np.char.split(x): Here the np.char.split() is called with x as an argument to split the string element of x into a list of substrings based on the default delimiter (space) and returns a 1-dimensional numpy array r containing a single element which is a list of the substrings.
Pictorial Presentation:
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics