Pandas Series: str.slice_replace() function
Series-str.slice_replace() function
The str.slice_replace() function is used to replace a positional slice of a string with another value.
Syntax:
Series.str.slice_replace(self, start=None, stop=None, repl=None)
Parameters:
Name | Description | Type/Default Value | Required / Optional |
---|---|---|---|
start | Left index position to use for the slice. If not specified (None), the slice is unbounded on the left, i.e. slice from the start of the string. | int | Optional |
stop | Right index position to use for the slice. If not specified (None), the slice is unbounded on the right, i.e. slice until the end of the string. | int | Optional |
repl | String for replacement. If not specified (None), the sliced region is replaced with an empty string. |
int | Optional |
Returns: Series or Index
Same type as the original object.
Example:
Python-Pandas Code:
import numpy as np
import pandas as pd
s = pd.Series(['p', 'pq', 'pqr', 'pqsr', 'pqrst'])
s
Output:
0 p 1 pq 2 pqr 3 pqsr 4 pqrst dtype: object
Example - Specify just start, meaning replace start until the end of the string with repl:
Python-Pandas Code:
import numpy as np
import pandas as pd
s = pd.Series(['p', 'pq', 'pqr', 'pqsr', 'pqrst'])
s.str.slice_replace(1, repl='A')
Output:
0 pA 1 pA 2 pA 3 pA 4 pA dtype: object
Example - Specify just stop, meaning the start of the string to stop is replaced with repl, and the rest of the string is included:
Python-Pandas Code:
import numpy as np
import pandas as pd
s = pd.Series(['p', 'pq', 'pqr', 'pqsr', 'pqrst'])
s.str.slice_replace(stop=2, repl='A')
Output:
0 A 1 A 2 Ar 3 Asr 4 Arst dtype: object
Example - Specify start and stop, meaning the slice from start to stop is replaced with repl. Everything before or after start and stop is included as is:
Python-Pandas Code:
import numpy as np
import pandas as pd
s = pd.Series(['p', 'pq', 'pqr', 'pqsr', 'pqrst'])
s.str.slice_replace(start=1, stop=3, repl='A')
Output:
0 pA 1 pA 2 pA 3 pAr 4 pAst dtype: object
Previous: Series-str.slice() function
Next: Series-str.split() function
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/pandas/series/series-str-slice_replace.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics