 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- 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 Python code to filter palindrome names in a given dataframe
Result for printing palindrome names are −
Palindrome names are: Id Name 0 1 bob 2 3 hannah
To solve this, we will follow the below approaches −
Solution 1
- Define a dataframe 
- Create list comprehension inside set for loop to access all the values from df[‘Name’] column using i variable and set if condition to compare i==i[::-1] then add i value to the list 
l = [ i for i in df['Name'] if(i==i[::-1])]
- Finally, check the list values present in the df[‘Name’] column using isin() 
df[df['Name'].isin(l)]
Example
Let’s check the following code to get a better understanding −
import pandas as pd data = {'Id':[1,2,3,4,5],'Name':['bob','peter','hannah','james','david']} df = pd.DataFrame(data) print("DataFrame is:\n", df) l = [ i for i in df['Name'] if(i==i[::-1])] print("Palindrome names are:\n", df[df['Name'].isin(l)]) Output
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
Solution 2
- Define a dataframe 
- Apply lambda filter function to compare df[‘Name’] each values with reversed function returns same result or not. If the values are matched then store it as result list. 
result = list(filter(lambda x:(x=="".join(reversed(x))),df['Name']
- Finally, check the list values present in the df[‘Name’] column using isin() 
df[df['Name'].isin(result)]
Example
Let’s check the following code to get a better understanding −
import pandas as pd data = {'Id':[1,2,3,4,5],'Name':['bob','peter','hannah','james','david']} df = pd.DataFrame(data) print("DataFrame is:\n", df) result = list(filter(lambda x:(x=="".join(reversed(x))),df['Name'])) print("Palindrome names are:\n", df[df['Name'].isin(result)]) Output
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
