- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Write a program in Python to slice substrings from each element in a given series
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
Advertisements