Friday, December 27, 2024
Google search engine
HomeLanguagesHow to check if Pandas column has value from list of string?

How to check if Pandas column has value from list of string?

In this article, we are going to see how to check if the pandas column has a value from a list of strings in Python.

List of strings means a list contains strings as elements, we will check if the pandas dataframe has values from a list of strings and display them when they are present. We will get the dataframe columns where the strings in the list contain.

Create the sample dataframe:

Python3




#import pandas
import pandas
 
# create dataframe
data = pandas.DataFrame({'name': ['sireesha', 'priyank',
                                  'ojaswi', 'gnanesh'],
                         'subjects': ['java', 'networks',
                                      'c', 'c#']})
 
# display
data


Output:

Method 1: Use isin() function

In this scenario, the isin() function check the pandas column containing the string present in the list and return the column values when present, otherwise it will not select the dataframe columns.

Syntax: dataframe[dataframe[‘column_name’].isin(list_of_strings)]

where

  • dataframe is the input dataframe
  • list_of_strings is the list that contains strings
  • column_name is the column to check the list of strings present in that column

Example: Python program to check if pandas column  has a value from a list of strings

Python3




#import pandas
import pandas
 
# create dataframe
data = pandas.DataFrame({'name': ['sireesha', 'priyank',
                                  'ojaswi', 'gnanesh'],
                         'subjects': ['java', 'networks',
                                      'c', 'c#']})
 
# consider a list
list1 = ['sireesha', 'priyank']
 
# check the pandas name column
# contain the given list of strings
print(data[data['name'].isin(list1)])
 
# consider a list
list2 = ['java', 'c']
 
# check the pandas subjects column
# contain the given list of strings
print(data[data['subjects'].isin(list2)])


Output:

Method 2: Using NumPy

Here NumPy also uses isin() operator to check if pandas column has a value from a list of strings.

Syntax: dataframe[~numpy.isin(dataframe[‘column’], list_of_value)]

Example:

Python3




# import pandas
import pandas
 
# import numpy
import numpy
 
# create dataframe
data = pandas.DataFrame({'name': ['sireesha', 'priyank',
                                  'ojaswi', 'gnanesh'],
                         'subjects': ['java', 'networks',
                                      'c', 'c#']})
 
# consider a list
list1 = ['sireesha', 'priyank']
 
# check the pandas name column
# contain the given list of strings
print(data[data['name'].isin(list1)])
 
# consider a list
list2 = ['java', 'c']
 
# check the pandas subjects column
# contain the given list of strings
data[~numpy.isin(data['subjects'], list1)]


Output:

RELATED ARTICLES

Most Popular

Recent Comments