Sometimes, we want to select with complex criteria from a Python Pandas DataFrame.
In this article, we’ll look at how to select with complex criteria from a Python Pandas DataFrame.
How to select with complex criteria from a Python Pandas DataFrame?
To select with complex criteria from a Python Pandas DataFrame, we can call the query
method.
For instance, we write
import pandas as pd
from random import randint
df = pd.DataFrame({'A': [randint(1, 9) for x in xrange(10)],
'B': [randint(1, 9) * 10 for x in xrange(10)],
'C': [randint(1, 9) * 100 for x in xrange(10)]})
df.query('B > 50 and C != 900')
to create a data frame df
with pd.DataFrame
.
Then we call df.query
with a string that has the conditions of the values we’re looking for and return that as a data frame.
Conclusion
To select with complex criteria from a Python Pandas DataFrame, we can call the query
method.