w3resource

NumPy String: numpy.char.partition() function

numpy.char.partition() function

The numpy.char.partition() function is used to partition the elements of a string array or a single string around a specified separator (substring).

This function is useful in -

  • Text processing: In natural language processing or text analysis tasks, we may need to split string arrays into parts based on a specific separator for further analysis, manipulation, or processing.
  • Data preprocessing: When working with data containing string arrays, we may need to partition the elements based on a specific separator to extract meaningful information or to restructure the data for further analysis.
  • Data cleaning: In some cases, we may need to correct inconsistencies within a dataset by partitioning string elements around a specific separator and extracting relevant information

Syntax:

numpy.char.partition(a, sep)

Parameters:

Name Description Required /
Optional
a: array_like, {str, unicode} Input array. Required
sep: {str, unicode} Separator to split each string element in a. Required

Return value:

Output array of str or unicode, depending on input type. The output array will have an extra dimension with 3 elements per input element.

Example: Partitioning strings using NumPy char.partition()

import numpy as np
x = "Python Exercises, Practice, Solution"
print("Original string:")
print(x)
print("\nHere separator is 'Practice'")
print(np.char.partition(x, 'Practice'))
print("\nHere separator is 'Exercises'")
print(np.char.partition(x, 'Exercises'))
print("\nHere separator is ','")
print(np.char.partition(x, ','))

Output:

Original string:
Python Exercises, Practice, Solution

Here separator is 'Practice'
['Python Exercises, ' 'Practice' ', Solution']

Here separator is 'Exercises'
['Python ' 'Exercises' ', Practice, Solution']

Here separator is ','
['Python Exercises' ',' ' Practice, Solution'] 

In the above example, the numpy.char.partition() function is used to demonstrate how to partition a string around different specified separators using NumPy.

Pictorial Presentation:

NumPy String operation: partition() function

Pictorial Presentation:

NumPy String operation: partition() function

Python - NumPy Code Editor:

Previous: lstrip()
Next: replace()



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/numpy/string-operations/partition.php