Search code examples
pythonpandascrosstabcontingency

Getting each element in Pandas crosstab


I have a dataset given below:

a,b,c
1,1,1
1,1,1
1,1,2
2,1,2
2,1,1
2,2,1

I created crosstab with pandas:

 cross_tab = pd.crosstab(index=a, columns=[b, c], rownames=['a'], colnames=['b', 'c'])

my crosstab is given as an output:

b        1     2
c        1  2  1
a        
1        2  1  0
2        1  1  1

I want to iterate over this crosstab for given each a,b and c values. How can I get values such as cross_tab[a=1][b=1, c=1]? Thank you.


Solution

  • You can use slicers:

    a,b,c = 1,1,1
    idx = pd.IndexSlice
    print (cross_tab.loc[a, idx[b,c]])
    2
    

    You can also reshape df by DataFrame.unstack, reorder_levels and then use loc:

    a = cross_tab.unstack().reorder_levels(('a','b','c'))
    print (a)
    a  b  c
    1  1  1    2
    2  1  1    1
    1  1  2    1
    2  1  2    1
    1  2  1    0
    2  2  1    1
    dtype: int64
    
    print (a.loc[1,1,1])
    2