Saturday, December 28, 2024
Google search engine
HomeLanguagesHow to split the element of a given NumPy array with spaces?

How to split the element of a given NumPy array with spaces?

To split the elements of a given array with spaces we will use numpy.char.split(). It is a function for doing string operations in NumPy. It returns a list of the words in the string, using sep as the delimiter string for each element in arr.

Parameters:
arr : array_like of str or unicode.Input array.
sep : [ str or unicode, optional] specifies the separator to use when splitting the string.
maxsplit : how many maximum splits to do.

Returns : [ndarray] Output Array containing of list objects.

Example 1:

Python3




import numpy as np
 
 
# Original Array
array = np.array(['PHP C# Python C Java C++'], dtype=np.str)
print(array)
 
# Split the element of the said array with spaces
sparr = np.char.split(array)
print(sparr)


Output :

['PHP C# Python C Java C++']
[list(['PHP', 'C#', 'Python', 'C', 'Java', 'C++'])]

Time Complexity: O(1) – The time complexity of importing a module is considered constant time.
Auxiliary Space: O(1) – The original array and split array are both stored in memory, which does not change with the size of the input. Therefore, the auxiliary space is constant.

Example 2:

Python3




import numpy as np
 
 
# Original Array
array = np.array(['Geeks For Geeks'], dtype=np.str)
print(array)
 
# Split the element of the said array
# with spaces
sparr = np.char.split(array)
print(sparr)


Output: 

['Geeks For Geeks']
[list(['Geeks', 'For', 'Geeks'])]

Time complexity: O(n), where n is the length of the input array.
Auxiliary space: O(n), where n is the length of the input array. 

Example 3:

Python3




import numpy as np
 
 
# Original Array
array = np.array(['DBMS OOPS DS'], dtype=np.str)
print(array)
 
# Split the element of the said array
# with spaces
sparr = np.char.split(array)
print(sparr)


Output:

['DBMS OOPS DS']
[list(['DBMS', 'OOPS', 'DS'])]

The time complexity of the code is O(n), where n is the length of the input string.

The auxiliary space complexity of the code is O(n),

RELATED ARTICLES

Most Popular

Recent Comments