Plumblei
Plumblei

Reputation: 11

Contingency table in Python

Given two lists of equal length, how can I construct a contingency table in a truly pythonic way? I know about confusion_matrix from skit-learn, but are there 'manual' and effective ways to do that?

Upvotes: 1

Views: 1094

Answers (1)

nitin
nitin

Reputation: 7358

You can use the pandas library to create the table shown in the wikipedia example, like so,

import pandas as pd
right_handed = [43, 44]
left_handed = [9,4]
df = pd.DataFrame({'right': right_handed, 'left': left_handed}, index = ['males', 'females'])

This yields a DataFrame, like so,

In [3]:

print (df)

         left  right
males       9     43
females     4     44

You can then use sum to get the totals,

print (df.left.sum())    
print (df.right.sum())

13
87

In [7]:

print (df.ix['males'].sum())
print (df.ix['females'].sum())

52
48

Upvotes: 2

Related Questions