How to create an advanced search function in pandas

Pandas offers amazing querying options for your data analysis projects. There are several ways of doing this, in our example we will use the str.contains() pandas attribute(NB: Not method).

Let's develop a querying function that will take 6 parameters for searching through 6 columns. How would we do that? First off;

import pandas as pd

Let's create our dataframe to run our query function through the columns. So;

df = pd.read_csv('csv_file_location_here')

Create the function, taking 6 parameters (searching through 6 columns in our dataframe by keywords and not strict on words inputed). We will call our function 'search' taking 6 parameters, a to f.

def search(a, b, c, d, e, f):

Next we will create a variable, for this example we will name it 'show'. So the below code simply states, we are creating daframes showing columns - 'Company Name', 'Category', 'Address', 'City', 'Email1', and 'Website'.

So for each dataframe we are searching for keywords, in which the parameters hold for us and initialize during the function call. (When we pass in the keywords during the function call). We don't want our search to be case sensitive (search by small letters) so we set 'case' to False and set 'na' to False as well(to avoid Nan values).

Finally we pass the entire 6 dataframes( in this case; columns) into the main dataframe at the beginning 'df[' and return 'show'.

Once we call the function search, we are expected to search by 6 fields; inputs (columns).

show = df[(df["Company Name"].str.contains(a, na=False, case=False)) & (df["Category"].str.contains(b, case=False, na=False)) & (df["Address"].str.contains(c, case=False, na=False)) & (df["City"].str.contains(d, case=False, na=False)) & (df["Email1"].str.contains(e, case=False, na=False)) & (df["Website"].str.contains(f, case=False, na=False))]
    return show

That's it. A function to search through 6 columns and provide as a table based on our search queries through all 6 columns. Lovely!

If you need assistance with your projects feel free to email me at info@airgad.com or whatsapp Jesse stay safe!