Pandas dataframe select rows where a list-column contains any of a list of strings

Given a pandas dataframe, we have to select rows where a list-column contains any of a list of strings.
Submitted by Pranit Sharma, on November 11, 2022

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.

Selecting rows where a list-column contains any of a list of strings

We are given a DataFrame with multiple columns, where a specific column only contains the list of strings.

We need to extract a DataFrame containing only those rows, that contain some specific strings enclosed in a list.

A list is a collection of heterogeneous elements and it is mutable. Tuples are also another built-in data type of python used to store heterogeneous elements.

The string is a group of characters, these characters may consist of all the lower case, upper case, and special characters present on the keyboard of a computer system. A string is a data type and the number of characters in a string is known as the length of the string.

Let us understand with the help of an example,

Python code to select rows where a list-column contains any of a list of strings

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a dictionary
d = {
    'code':[1,2,3,4],
    'flowers':[['lily','rose'],['lotus','rose','sunflower'],['lily'],['orchid']]
}

# Creating DataFrame
df = pd.DataFrame(d)

# Display dataframe
print('Original DataFrame:\n',df,'\n')

# Defining some specific strings
specific = ['rose','lily']

# Selecting some specific strings
res = df[pd.DataFrame(df.flowers.tolist()).isin(specific).any(1).values]

# Display result
print("Result:\n",res)

Output:

Example: Select rows where a list-column contains any of a list of strings

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.