Write a Python code to filter palindrome names in a given dataframe

PythonPandasServer Side ProgrammingProgramming

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
raja
Published on 12-Feb-2021 11:01:40
Advertisements