Python - Filter Pandas DataFrame with numpy

PythonServer Side ProgrammingProgramming

The numpy where() method can be used to filter Pandas DataFrame. Mention the conditions in the where() method. At first, let us import the required libraries with their respective alias

import pandas as pd
import numpy as np

We will now create a Pandas DataFrame with Product records 

dataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"],"Opening_Stock": [300, 700, 1200, 1500],"Closing_Stock": [200, 500, 1000, 900]})

Use numpy where() to filter DataFrame with 2 Conditions

resValues1 = np.where((dataFrame['Opening_Stock']>=700) & (dataFrame['Closing_Stock']< 1000))

print"\nFiltered DataFrame Value = \n",dataFrame.loc[resValues1]

Let us use numpy where() again to filter DataFrame with 3 conditions

resValues2 = np.where((dataFrame['Opening_Stock']>=500) & (dataFrame['Closing_Stock']< 1000) & (dataFrame['Product'].str.startswith('C')))

Example

Following is the complete code

import pandas as pd
import numpy as np

dataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"],"Opening_Stock": [300, 700, 1200, 1500],"Closing_Stock": [200, 500, 1000, 900]})

print"DataFrame...\n",dataFrame

# using numpy where() to filter DataFrame with 2 Conditions
resValues1 = np.where((dataFrame['Opening_Stock']>=700) & (dataFrame['Closing_Stock']< 1000))

print"\nFiltered DataFrame Value = \n",dataFrame.loc[resValues1]

# using numpy where() to filter DataFrame with 3 conditions
resValues2 = np.where((dataFrame['Opening_Stock']>=500) & (dataFrame['Closing_Stock']< 1000) & (dataFrame['Product'].str.startswith('C')))

print"\nFiltered DataFrame Value = \n",dataFrame.loc[resValues2]

Output

This will produce the following output

DataFrame...
   Closing_Stock   Opening_Stock   Product
0          200            300     SmartTV
1          500            700     ChromeCast
2         1000           1200     Speaker
3          900           1500     Earphone

Filtered DataFrame Value =
   Closing_Stock   Opening_Stock   Product
1           500             700    ChromeCast
3           900            1500    Earphone

Filtered DataFrame Value =
   Closing_Stock   Opening_Stock   Product
1           500             700    ChromeCast
raja
Published on 14-Sep-2021 08:32:03
Advertisements