fred.schwartz
fred.schwartz

Reputation: 2155

Cross Tab and Chi Square Test in Python

I am trying to learn python.

I have a table, with a persons preference (A or B

    Preference
0      A
1      A
2      B
3      A
4      B

I wanted to make a cross tab table and then perform a Chi squared test

So the cross tab table is

A   number of A's
B   number of B's

and then a chi square test giving the pvalue and degrees of freedom

I know how to do this in R

tbl= xtabs( ~ Preference, data=df)
chisq.test(tbl)

But can't figure out how to do it in python, though it seems fairly basic.

Can anyone help?

Upvotes: 0

Views: 633

Answers (1)

shyam_gupta
shyam_gupta

Reputation: 328

For doing crosstab

you may use pd.crosstab(df.index,df.preferences)

for chi square test use scipy module as support

from scipy.stats import chi2_contingency

stat, p, dof, expected = chi2_contingency(df)

Upvotes: 1

Related Questions