Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding filter to pandas pivot table

I would like to add a filtering condition to a pivot table, like this:

(Select the values of v2 equal to 'A')

pd.pivot_table(df,index=['v1'],columns=['v2'=='A'],values=['v3'],aggfunc='count')

Is that possible?

like image 868
progster Avatar asked Apr 05 '17 15:04

progster


1 Answers

This is an extension of Grr's answer.

Using their suggestion:

pd.pivot_table(df[df.v3 == some_value], index='v1', columns='A', values='v3', aggfunc='count')

Produces an error:

"TypeError: pivot_table() got multiple values for argument 'values'"

I made a slight tweak, and it works for me:

df[df.v3 == some_value].pivot_table(index='v1', columns='A', values='v3', aggfunc='count')

For adding multiple filters: Use &, | operators with a set of () to specify the priority. Using and,or results in an error.

df[(df.v3 == some_value) & (df.v4 == some_value)].pivot_table(index='v1', columns='A', values='v3', aggfunc='count')
like image 192
Josh Janjua Avatar answered Sep 23 '22 19:09

Josh Janjua