NumPy String: numpy.char.translate() function
numpy.char.translate() function
For each element in a given array, the numpy.char.translate() function returns a copy of the string where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table.
The function is useful for data cleaning and manipulation tasks where certain characters or patterns need to be replaced or removed from the strings in an array.
Syntax:
numpy.char.translate(a, table, deletechars=None)
Parameters:
Name | Description | Required / Optional |
---|---|---|
a: | array-like of str or unicode | Required |
table: | str of length 256 | Required |
deletechars | Delete characters. | Optional |
Return value:
out [ndarray] Output array of str or unicode, depending on input type.
Example: Using numpy.char.translate() function to delete characters from a string
>>> import numpy as np
>>> table = '*'
>>> x = np.char.translate('The quick brown fox', table, deletechars=None)
>>> x
array('The quick brown fox', dtype='<U19')
In the above example the input string is 'The quick brown fox' and the table used for translation is '*'. Since deletechars argument is set to None, this table is used to delete characters from the input string. The resulting string is stored in the variable x which is an array of dtype '<U19'.
Example-2: numpy.char.translate() function
>>> import numpy as np
>>> table = '256'
>>> x = np.char.translate('The quick brown fox jumps over the lazy dog', table, deletechars=None)
>>> x
array('The quick brown fox jumps over the lazy dog', dtype='<U43')
Python - NumPy Code Editor:
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://w3resource.com/numpy/string-operations/translate.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics