Applying multiple filter on pandas pivot table

Viewed 533

How can we apply multiple filter on piviot_table?

I have a dataframe as df

I'm able to apply one filter on it by

pivot = df.query('Brand == ["HTC", "APPLE"]'
                ).pivot_table(index = ['Outlet'], 
                columns = ['Material'],
                values = ['Sales'],
                aggfunc = np.sum, fill_value=0, margins=True)

The above code is working correct with one filter Brand, but how do apply one or more filter to this? In the below code if you see I have tried to add but I was getting an error which didn't work. Maybe I'm not giving the second filter correctly.

pivot = df.query('Brand == ["HTC", "APPLE"]', 'City == ["Delhi", "Mumbai"]'
                ).pivot_table(index = ['Outlet'], 
                columns = ['Material'],
                values = ['Sales'],
                aggfunc = np.sum, fill_value=0, margins=True)

Does anyone know how do I do this?

1 Answers

You may need a logical operator in the condition, e.g:

pivot = df.query('Brand == ["HTC", "APPLE"]' and 'City == ["Delhi", "Mumbai"]'
                ).pivot_table(index = ['Outlet'], 
                columns = ['Material'],
                values = ['Sales'],
                aggfunc = np.sum, fill_value=0, margins=True)
Related