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
Write a Python code to filter palindrome names in a given dataframe
A palindrome is a word that reads the same forwards and backwards. In this tutorial, we'll learn how to filter palindrome names from a Pandas DataFrame using different approaches.
Using List Comprehension
This approach uses list comprehension to identify palindromes by comparing each name with its reverse using slicing [::-1] ?
import pandas as pd
data = {'Id': [1, 2, 3, 4, 5], 'Name': ['bob', 'peter', 'hannah', 'james', 'david']}
df = pd.DataFrame(data)
print("DataFrame is:")
print(df)
# Find palindrome names using list comprehension
palindromes = [name for name in df['Name'] if name == name[::-1]]
result = df[df['Name'].isin(palindromes)]
print("\nPalindrome names are:")
print(result)
DataFrame is: Id Name 0 1 bob 1 2 peter 2 3 hannah 3 4 james 4 5 david Palindrome names are: Id Name 0 1 bob 2 3 hannah
Using Lambda Function with Filter
This approach uses a lambda function with filter() to check if each name equals its reversed version using reversed() ?
import pandas as pd
data = {'Id': [1, 2, 3, 4, 5], 'Name': ['bob', 'peter', 'hannah', 'james', 'david']}
df = pd.DataFrame(data)
print("DataFrame is:")
print(df)
# Find palindrome names using filter with lambda
palindromes = list(filter(lambda x: (x == "".join(reversed(x))), df['Name']))
result = df[df['Name'].isin(palindromes)]
print("\nPalindrome names are:")
print(result)
DataFrame is: Id Name 0 1 bob 1 2 peter 2 3 hannah 3 4 james 4 5 david Palindrome names are: Id Name 0 1 bob 2 3 hannah
Using Direct Boolean Indexing
We can also filter palindromes directly using boolean indexing without creating intermediate lists ?
import pandas as pd
data = {'Id': [1, 2, 3, 4, 5], 'Name': ['bob', 'peter', 'hannah', 'james', 'david']}
df = pd.DataFrame(data)
print("DataFrame is:")
print(df)
# Direct boolean indexing
result = df[df['Name'] == df['Name'].str[::-1]]
print("\nPalindrome names are:")
print(result)
DataFrame is: Id Name 0 1 bob 1 2 peter 2 3 hannah 3 4 james 4 5 david Palindrome names are: Id Name 0 1 bob 2 3 hannah
Comparison
| Method | Performance | Readability | Best For |
|---|---|---|---|
| List Comprehension | Good | High | General use |
| Lambda with Filter | Moderate | Moderate | Functional programming style |
| Boolean Indexing | Best | High | Large datasets |
Conclusion
All three methods successfully filter palindrome names from a DataFrame. Boolean indexing is most efficient for large datasets, while list comprehension offers the best balance of readability and performance.
