简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM