LoginSignup
2
3

More than 5 years have passed since last update.

python pandas 統計 cross 集計とカイ二乗検定

Last updated at Posted at 2018-05-04

1, scipyの出力の2番目がp値
chi2, p, dof, ex = stats.chi2_contingency(crossed)

2, クロス集計表を作る。
N(%)の形式のテーブルを作るのが目的だったが、これが大変。
DataFrameとDataFrameは足算するとブロードキャストできる。しかし、足す時に"("などの文字列を挿入することができない。(私にはできない)

NumpyのArrayも足算は基本的にブロードキャスト(たぶん)。しかし、同様に文字列挿入ができない。

こねくり回して、結局以下のようにデータフレームのセル(1マス?)要素に一つずつアクセスして、str()で文字列に変換して、合体。しんどい。
いいやり方見つけたら、修正する。

以下のcrはpandas はcross table(dataframe形式)

def cross_table(df,colname1,colname2):
    cr = pd.crosstab(df[colname1],df[colname2])
    #%計算
    arr = np.array([
        [cr["FALSE"][0] / (cr["FALSE"][0]+cr["FALSE"][1]),cr["TRUE"][0] / (cr["TRUE"][0]+cr["TRUE"][1])],
        [cr["FALSE"][1] / (cr["FALSE"][0]+cr["FALSE"][1]),cr["TRUE"][1] / (cr["TRUE"][0]+cr["TRUE"][1])]
        ])
    arr = arr * 100 #%に
    arr = arr.round(2) #四捨五入
    #%のテーブルと合体
    new_cross_table = np.array([
            [cr.iloc[0, 0],str(cr.at[0,"FALSE"]) + "("+ str(arr[0][0]) + ")", str(cr.at[0,"TRUE"])+"("+ str(arr[0][1]) + ")"],
            [cr.iloc[1, 0],str(cr.at[1,"FALSE"]) + "("+ str(arr[1][0]) + ")", str(cr.at[1,"TRUE"])+"("+ str(arr[1][1]) + ")"]
            ])
    #形式をデータフレームにもどす
    df_cr = pd.DataFrame(new_cross_table,columns=["Defect","FALSE","TRUE"])
    df_cr.index.name = colname1
    df_cr.columns.name = colname2
    return cr,arr,df_cr

参考リンク
http://lagrange.univ-lyon1.fr/docs/scipy/0.17.1/generated/scipy.stats.chi2_contingency.html

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3