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.
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
You may be able to use a DoubleDict as shown in recipe 578224 on the Python Cookbook.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With