To query the columns of a Pandas DataFrame, use the query(). We are querying to filter records. At first, let us create a Pandas DataFrame
dataFrame = pd.DataFrame({"Product": ["SmartTV", "PenDrive", "Speaker", "Earphone"],"Opening_Stock": [300, 700, 1200, 1500],"Closing_Stock": [200, 500, 1000, 900]})
Using query() to query columns with conditions −
print(dataFrame.query('Opening_Stock >=500 & Closing_Stock < 1000 & Product.str.startswith("P").values'))
Example
Following is the complete code −
import pandas as pd dataFrame = pd.DataFrame({"Product": ["SmartTV", "PenDrive", "Speaker", "Earphone"],"Opening_Stock": [300, 700, 1200, 1500],"Closing_Stock": [200, 500, 1000, 900]}) print"DataFrame...\n",dataFrame # using query() to query columns print"\nQuerying columns to filter records...\n" print(dataFrame.query('Opening_Stock >=500 & Closing_Stock < 1000 & Product.str.startswith("P").values'))
Output
This will produce the following output −
DataFrame... Closing_Stock Opening_Stock Product 0 200 300 SmartTV 1 500 700 PenDrive 2 1000 1200 Speaker 3 900 1500 Earphone Querying columns to filter records... Closing_Stock Opening_Stock Product 1 500 700 PenDrive