Slice Substrings from Each Element in a Given Series using Python



Assume, you have a series and the result for slicing substrings from each element in series as,

0    Ap
1    Oa
2    Mn
3    Kw

To solve this, we will follow the below approaches −

Solution 1

  • Define a series

  • Apply str.slice function inside start=0,stop-4 and step=2 to slice the substring from the series.

data.str.slice(start=0,stop=4,step=2)

Example

Let’s check the following code to get a better understanding −

import pandas as pd
data = pd.Series(['Apple','Orange','Mango','Kiwis'])
print(data.str.slice(start=0,stop=4,step=2))

Output

0    Ap
1    Oa
2    Mn
3    Kw

Solution 2

  • Define a series

  • Apply string index slice to start from 0 to end range as 4 and step value as 2. It is defined below,

data.str[0:4:2]

Example

Let’s check the following code to get a better understanding −

import pandas as pd
data = pd.Series(['Apple','Orange','Mango','Kiwis'])
print(data.str[0:4:2])

Output

0    Ap
1    Oa
2    Mn
3    Kw
Updated on: 2021-02-25T06:58:31+05:30

104 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements