Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Write a program in Python to slice substrings from each element in a given series
In Pandas, you can slice substrings from each element in a Series using string methods. This is useful for extracting specific characters or patterns from text data.
Creating a Sample Series
Let's start by creating a Series with fruit names ?
import pandas as pd
data = pd.Series(['Apple', 'Orange', 'Mango', 'Kiwis'])
print("Original Series:")
print(data)
Original Series: 0 Apple 1 Orange 2 Mango 3 Kiwis dtype: object
Method 1: Using str.slice()
The str.slice() method allows you to specify start, stop, and step parameters ?
import pandas as pd
data = pd.Series(['Apple', 'Orange', 'Mango', 'Kiwis'])
result = data.str.slice(start=0, stop=4, step=2)
print("Sliced substrings using str.slice():")
print(result)
Sliced substrings using str.slice(): 0 Ap 1 Oa 2 Mn 3 Kw dtype: object
Method 2: Using String Indexing
You can also use Python's slice notation with the str accessor ?
import pandas as pd
data = pd.Series(['Apple', 'Orange', 'Mango', 'Kiwis'])
result = data.str[0:4:2]
print("Sliced substrings using string indexing:")
print(result)
Sliced substrings using string indexing: 0 Ap 1 Oa 2 Mn 3 Kw dtype: object
Understanding the Parameters
Both methods use the same slicing parameters:
- start=0: Begin from the first character (index 0)
- stop=4: End before the 5th character (index 4)
- step=2: Take every 2nd character
Additional Examples
Here are more slicing patterns you can use ?
import pandas as pd
data = pd.Series(['Apple', 'Orange', 'Mango', 'Kiwis'])
print("First 3 characters:")
print(data.str[:3])
print("\nLast 2 characters:")
print(data.str[-2:])
print("\nEvery 2nd character:")
print(data.str[::2])
First 3 characters: 0 App 1 Ora 2 Man 3 Kiw dtype: object Last 2 characters: 0 le 1 ge 2 go 3 is dtype: object Every 2nd character: 0 Ape 1 Orne 2 Mno 3 Kis dtype: object
Comparison
| Method | Syntax | Best For |
|---|---|---|
str.slice() |
data.str.slice(0, 4, 2) |
Explicit parameter names |
| String indexing | data.str[0:4:2] |
Concise Python-style slicing |
Conclusion
Both str.slice() and string indexing produce identical results for substring extraction. Use string indexing for concise code or str.slice() when you need explicit parameter names for clarity.
Advertisements
