Home »
Python »
Python Programs
Python - How to query if a list-type column contains something?
Given a Pandas dataframe, we have to query if a list-type column contains something.
By Pranit Sharma Last updated : September 29, 2023
Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.
Problem statement
Suppose, we have a DataFrame that contains different automobile brands and their models.
Querying if a list-type column contains something
We will check if we have a particular string in that column list or not. For this purpose, we will just loop over each column that is of list type and we will check whether our string is in that list or not.
Let us understand with the help of an example,
Python program to query if a list-type column contains something
# Importing pandas package
import pandas as pd
# Creating two dictionaries
d1 = {'Vehicles':[
['Scorpion','XUV','Bolero','Thar'],
['Altroz','Nexon','Thar','Harrier'],
['Creta','i20','Verna','Aalcasar']]}
# Creating DataFrame
df = pd.DataFrame(d1)
# Display the DataFrame
print("Original DataFrame:\n",df,"\n\n")
# Check if a value exists
res = df.Vehicles.apply(lambda x: 'Thar' in x)
# Display result
print("Result:\n",df[res],"\n")
Output
The output of the above program is:
Python Pandas Programs »