w3resource

Pandas Series: str.slice() function

Series-str.slice() function

The str.slice() function is used to slice substrings from each element in the Series or Index.

Syntax:

Series.str.slice(self, start=None, stop=None, step=None)
Pandas Series: str.slice() function

Parameters:

Name Description Type/Default Value Required / Optional
start Start position for slice operation. int Optional
stop Stop position for slice operation. int Optional
step  

Step size for slice operation.

int Optional

Returns: Series, Index, DataFrame or MultiIndex
Type matches caller unless expand=True (see Notes).

Example:

Python-Pandas Code:

import numpy as np
import pandas as pd
s = pd.Series(["tiger", "cat", "elephant"])
s

Output:

0       tiger
1         cat
2    elephant
dtype: object

Python-Pandas Code:

import numpy as np
import pandas as pd
s = pd.Series(["tiger", "cat", "elephant"])
s.str.slice(start=1)

Output:

0       iger
1         at
2    lephant
dtype: object

Python-Pandas Code:

import numpy as np
import pandas as pd
s = pd.Series(["tiger", "cat", "elephant"])
s.str.slice(stop=2)

Output:

0    ti
1    ca
2    el
dtype: object
Pandas Series: str.slice() function

Example - s.str.slice(step=2):

Python-Pandas Code:

import numpy as np
import pandas as pd
s = pd.Series(["tiger", "cat", "elephant"])
s.str.slice(start=0, stop=5, step=3)

Output:

0    te
1     c
2    ep
dtype: object

Example - Equivalent behaviour to:

Python-Pandas Code:

import numpy as np
import pandas as pd
s = pd.Series(["tiger", "cat", "elephant"])
s.str[0:5:3]

Output:

0    te
1     c
2    ep
dtype: object

Previous: Series-str.rstrip() function
Next: Series-str.slice_replace() function



Follow us on Facebook and Twitter for latest update.