How to check if Pandas column has value from list of string?
Last Updated :
07 Mar, 2023
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
data = pandas.DataFrame({ 'name' : [ 'sireesha' , 'priyank' ,
'ojaswi' , 'gnanesh' ],
'subjects' : [ 'java' , 'networks' ,
'c' , 'c#' ]})
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
data = pandas.DataFrame({ 'name' : [ 'sireesha' , 'priyank' ,
'ojaswi' , 'gnanesh' ],
'subjects' : [ 'java' , 'networks' ,
'c' , 'c#' ]})
list1 = [ 'sireesha' , 'priyank' ]
print (data[data[ 'name' ].isin(list1)])
list2 = [ 'java' , 'c' ]
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 numpy
data = pandas.DataFrame({ 'name' : [ 'sireesha' , 'priyank' ,
'ojaswi' , 'gnanesh' ],
'subjects' : [ 'java' , 'networks' ,
'c' , 'c#' ]})
list1 = [ 'sireesha' , 'priyank' ]
print (data[data[ 'name' ].isin(list1)])
list2 = [ 'java' , 'c' ]
data[~numpy.isin(data[ 'subjects' ], list1)]
|
Output:
Share your thoughts in the comments
Please Login to comment...