Write a program in Python to slice substrings from each element in a given series

PythonPandasServer Side ProgrammingProgramming

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
raja
Published on 12-Feb-2021 10:51:09
Advertisements