Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas crosstab, but with values from aggregation of third column

Here is my problem:

df = pd.DataFrame({'A': ['one', 'one', 'two', 'two', 'one'] ,
                   'B': ['Ar', 'Br', 'Cr', 'Ar','Ar'] ,
                   'C': [1, 0, 0, 1,0 ]})

I would like to generate something like output of pd.crosstab function, but values on the intersection of column and row should come from aggregation of third column:

    Ar,  Br, Cr
one 0.5 0  0
two 1  0  0

For example, there are two cases of 'one' and 'Ar' corresponding values in column 'C' are 1,0 we sum up values in column 'C' (0+1) and divide by number of values in column 'C', so we get (0+1)/2 =0.5. Whenever combination is not present we (like 'Cr' and 'one') we set it to zero. Any thoughts?

like image 931
user1700890 Avatar asked Sep 27 '16 22:09

user1700890


2 Answers

you can use pivot_table() method, which uses aggfunc='mean' per-default:

In [46]: df.pivot_table(index='A', columns='B', values='C', fill_value=0)
Out[46]:
B     Ar  Br  Cr
A
one  0.5   0   0
two  1.0   0   0
like image 89
MaxU - stop WAR against UA Avatar answered Nov 14 '22 22:11

MaxU - stop WAR against UA


I like groupby and unstack

df.groupby(['A', 'B']).C.mean().unstack(fill_value=0)

enter image description here

like image 44
piRSquared Avatar answered Nov 14 '22 22:11

piRSquared