8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

クラメールの連関係数の計算

Posted at

Pythonでクラメールの連関係数を計算するモジュールが見当たらなかったので自作しました.
計算方法はこちらを参考にしました.

cramerV.py
# -*- coding: utf-8 -*-

import numpy as np


def cramersV(x, y):
    """
    Calc Cramer's V.

    Parameters
    ----------
    x : {numpy.ndarray, pandas.Series}
    y : {numpy.ndarray, pandas.Series}
    """
    table = np.array(pd.crosstab(x, y)).astype(np.float32)
    n = table.sum()
    colsum = table.sum(axis=0)
    rowsum = table.sum(axis=1)
    expect = np.outer(rowsum, colsum) / n
    chisq = np.sum((table - expect) ** 2 / expect)
    return np.sqrt(chisq / (n * (np.min(table.shape) - 1)))


if __name__ == "__main__":
    import pandas as pd
    data = pd.DataFrame(
        {'science': ['like', 'like', 'like', 'like', 'like', 'like', 'like',
                     'like', 'like', 'like', 'like', 'like', 'like', 'like',
                     'like', 'like', 'like', 'like', 'like', 'like', 'like',
                     'like', 'like', 'like', 'like', 'like', 'like', 'like',
                     'like', 'like', 'like', 'dislike', 'dislike', 'dislike',
                     'dislike', 'dislike', 'dislike', 'dislike', 'dislike',
                     'dislike', 'dislike', 'dislike', 'dislike', 'dislike',
                     'dislike', 'dislike', 'dislike', 'dislike', 'dislike',
                     'dislike'],
         'math': ['like', 'like', 'like', 'like', 'like', 'like', 'like',
                  'like', 'like', 'like', 'like', 'like', 'like', 'like',
                  'like', 'like', 'like', 'like', 'like', 'like', 'like',
                  'like', 'like', 'like', 'dislike', 'dislike', 'dislike',
                  'dislike', 'dislike', 'dislike', 'dislike', 'like', 'like',
                  'like', 'like', 'like', 'like', 'dislike', 'dislike',
                  'dislike', 'dislike', 'dislike', 'dislike', 'dislike',
                  'dislike', 'dislike', 'dislike', 'dislike', 'dislike',
                  'dislike']})
    print cramersV(data['science'], data['math'])

8
6
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
8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?