カイ二乗検定|Logics of Blue

https://logics-of-blue.com/chi-squared-test/

ライブラリのインポート

In [1]:
# 必要なライブラリのインポート
import numpy as np
import pandas as pd
import scipy as sp
from scipy import stats

# 表示桁数の指定
%precision 3
Out[1]:
'%.3f'
In [2]:
# データを用意する
ab_test_data = pd.DataFrame({
  "button":["blue", "blue", "red", "red"],
  "result":["press", "not","press", "not"],
  "number":[70, 180, 30, 120]
})
print(ab_test_data)
  button  number result
0   blue      70  press
1   blue     180    not
2    red      30  press
3    red     120    not
In [3]:
# クロス集計表に変換する
cross_data = pd.pivot_table(
    data = ab_test_data,
    values ="number",
    aggfunc = "sum",
    index = "button",
    columns = "result"
)
print(cross_data)
result  not  press
button            
blue    180     70
red     120     30

カイ二乗検定の実行

In [4]:
# カイ二乗検定の実行
stats.chi2_contingency(cross_data, correction=False)
Out[4]:
(3.200, 0.074, 1, array([[ 187.5,   62.5],
        [ 112.5,   37.5]]))