编程语言
首页 > 编程语言> > 我们可以使用python为chisquare测试生成列联表吗?

我们可以使用python为chisquare测试生成列联表吗?

作者:互联网

我使用scipy.stats.chi2_contingency方法来获取卡方统计数据.我们需要将频率表即列联表作为参数.但我有一个特征向量,并希望自动生成频率表.我们有这样的功能吗?
我现在这样做:

def contigency_matrix_categorical(data_series,target_series,target_val,indicator_val):
  observed_freq={}
  for targets in target_val:
      observed_freq[targets]={}
      for indicators in indicator_val:
          observed_freq[targets][indicators['val']]=data_series[((target_series==targets)&(data_series==indicators['val']))].count()
  f_obs=[]
  var1=0
  var2=0
  for i in observed_freq:
      var1=var1+1
      var2=0
      for j in observed_freq[i]:
          f_obs.append(observed_freq[i][j]+5)
          var2=var2+1
  arr=np.array(f_obs).reshape(var1,var2)
  c,p,dof,expected=chi2_contingency(arr)
  return {'score':c,'pval':p,'dof':dof}

数据系列和目标系列是列值,另外两个是指标的名称.
有人可以帮忙吗?
谢谢

解决方法:

您可以使用pandas.crosstab从DataFrame生成列联表.从文档:

Compute a simple cross-tabulation of two (or more) factors. By default computes a frequency table of the factors unless an array of values and an aggregation function are passed.

以下是一个用法示例:

import numpy as np
import pandas as pd
from scipy.stats import chi2_contingency

# Some fake data.
n = 5  # Number of samples.
d = 3  # Dimensionality.
c = 2  # Number of categories.
data = np.random.randint(c, size=(n, d))
data = pd.DataFrame(data, columns=['CAT1', 'CAT2', 'CAT3'])

# Contingency table.
contingency = pd.crosstab(data['CAT1'], data['CAT2'])

# Chi-square test of independence.
c, p, dof, expected = chi2_contingency(contingency)

以下数据表

生成以下列联表

然后,scipy.stats.chi2_contingency(意外事件)返回(0.052,0.819,1,数组([[1.6,0.4],[2.4,0.6]])).

标签:statsmodels,python,scipy,statistics,chi-squared
来源: https://codeday.me/bug/20190825/1714561.html