NumPy: replace() function
numpy.core.defchararray.replace() function
For each element in a given array numpy.core.defchararray.replace() function returns a copy of the string with all occurrences of substring old replaced by new.
Calls str.replace element-wise.
Version: 1.15.0
Syntax:
numpy.core.defchararray.replace(a, old, new, count=None)
Parameter:
Name | Description | Required / Optional |
---|---|---|
a | Given array-like of string or unicode | Required |
old, new | Given old or new string or unicode | Required |
count | If the optional argument count is given, only the first count occurrences are replaced. | Optional |
Return value:
out : ndarray - Output array of str or unicode, depending on input type
Note:
The 'chararray' class exists for backwards compatibility with Numarray, it is not recommended for new development. Starting from numpy 1.4, if one needs arrays of strings, it is recommended to use arrays of 'dtype' 'object_', 'string_' or 'unicode_', and use the free functions in the 'numpy.char' module for fast vectorized string operations.
Some methods will only be available if the corresponding string method is available in your version of Python.
The preferred alias for 'defchararray' is 'numpy.char'.
Example-1: numpy.replace() function
>>> import numpy as np
>>> x = np.char.replace('The quick brown fox', 'fox', 'wolf')
>>> x
array('The quick brown wolf', dtype='<U20')
Pictorial Presentation:
Example-2: numpy.replace() function
>>> import numpy as np
>>> x = np.char.replace('The quick fox brown fox', 'fox', 'wolf', count=0)
>>> x
array('The quick fox brown fox', dtype='<U23')
Pictorial Presentation:
Example-3: numpy.replace() function
>>> import numpy as np
>>> x = np.char.replace('The quick fox brown fox', 'fox', 'wolf', count=1)
>>> x
array('The quick wolf brown fox', dtype='<U24')
Pictorial Presentation:
Example-4: numpy.replace() function
>>> import numpy as np
>>> x = np.char.replace('The quick fox brown fox', 'fox', 'wolf', count=2)
>>> x
array('The quick wolf brown wolf', dtype='<U25')
Pictorial Presentation:
Python - NumPy Code Editor:
Previous:
partition()
Next:
rjust()
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework