Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a 2-way table in python? [closed]

Tags:

python

How can I create a 2-way table in python? I have 2 categorical variables in a data set and would like to look at the relationship between the 2 variables by creating a 2-way table. Thank you.

like image 309
Tarek Deeb Avatar asked Nov 21 '25 10:11

Tarek Deeb


2 Answers

There's a bidict package:

>>> from bidict import bidict
>>> husbands2wives = bidict({'john': 'jackie'})
>>> husbands2wives['john']  # the forward mapping is just like with dict
'jackie'
>>> husbands2wives[:'jackie']  # use slice for the inverse mapping
'john'

You can install it using pip install bidict.


EDIT: For your actual problem - if I understand you correctly - I would use pandas:

# data.csv
Gender Height GPA HS GPA Seat WtFeel Cheat 
Female 64 2.60 2.63 M AboutRt No 1 
Male 69 2.70 3.72 M AboutRt No 2 
Female 66 3.00 3.44 F AboutRt No 3 
Female 63 3.11 2.73 F AboutRt No 4 
Male 72 3.40 2.35 B OverWt No 0

In [1]: import pandas as pd

In [2]: df = pd.read_csv('data.csv', sep = '\s')

In [3]: grouped = df.groupby(['Gender', 'Seat'])

In [4]: grouped.size()
Out[4]: 
Gender  Seat   
Female  AboutRt    3
Male    AboutRt    1
        OverWt     1
dtype: int64
like image 181
root Avatar answered Nov 23 '25 00:11

root


You may be able to use a DoubleDict as shown in recipe 578224 on the Python Cookbook.

like image 41
Noctis Skytower Avatar answered Nov 22 '25 22:11

Noctis Skytower