How to select with complex criteria from pandas DataFrame?

Given a DataFrame, we have to select with complex criteria from it.
Submitted by Pranit Sharma, on May 13, 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 the data. DataFrame can be created with the help of python dictionaries or lists but in the real world, CSV files are imported and then converted into DataFrames. Sometimes, DataFrames are first written into CSV files. Here, we are creating a DataFrame and then we will select a particular row using the pandas.DataFrame.query() method.

pandas.DataFrame.query() Method

It allows us to apply any condition or query in the DataFrame. It returns the data after filtering it through the query.


DataFrame.query(expr, inplace=False, **kwargs)

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example:

# Importing pandas package
import pandas as pd

# creating a dictionary of student marks
d = {

# Now we will create DataFrame

# Viewing the DataFrame

# Applying a query
df1 = df.loc[df.query(
    'Runs >= 12000'

# Display df1
print("Filtered DataFrame\n",df1)


Example: select with complex criteria from DataFrame

Python Pandas Programs »



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

© some rights reserved.