Pandas filtering on dynamic columns with dynamic values

Viewed 13

I'm having a pandas Dataframe and I want to perform filtering on that dataset dynamically. Like

enter image description here

Now I have list of filters like:

{
  "Department Name": "Engineering",
  "Account ID": "511110"
}

Basically, In pandas if I want to get Total Sale for Department Name: "Engineering" and Account ID: 511110. then I have to mention these filtering parameters as

filtered_df = df.loc[(df["Department Name"] == "Engineering") & (df["Account ID"] == 511110)]
total_sales = filtered_df["Total Sales"].sum()

Now think about, if these filtering parameters are dynamic then we need to add filters in loop

for field_name in filters:
    filter_val = filters[field_name]
    df = df.loc[df[field_name]==filter_val

total_sales = df["Total Sales"].sum()

So I'm trying to find a way, where I can add all the filtering parameters as a list to pandas dataframe and it provides me filtered records. So I can apply other operations on that.

Thanks in Advance.

0 Answers
Related