def contingency(fo, alpha=0.05):
    " 列联表分析：(观察频数表分析)\n    # 预增加一个各类别之间的距离\n    1、生成TGI指数、TWI指数、CHI指数\n    2、独立性检验\n    3、当两个变量不显著时，考虑单个之间的显著性\n    返回字典格式\n    chi_test: 卡方检验结果，1:显著；0:不显著；-1：期望值不满足条件\n    coef: 包含chi2、p值、V相关系数\n    log: 记录一些异常情况\n    FO: 观察频数\n    FE: 期望频数\n    TGI：fo/fe\n    TWI：fo-fe\n    CHI：sqrt((fo-fe)(fo/fe-1))*sign(fo-fe)\n    significant:{\n    .'result': 显著性结果[1(显著),0(不显著),-1(fe小于5的过多)]\n    .'pvalue':\n    .'method': chi_test or fisher_test\n    .'vcoef':\n    .'threshold':\n    }\n    summary:{\n    .'summary': 结论提取\n    .'fit_test': 拟合优度检验\n    .'chi_std':\n    .'chi_mean':\n    "
    import scipy.stats as stats
    cdata = {}
    if isinstance(fo, pd.core.series.Series):
        fo = pd.DataFrame(fo)
    if (not isinstance(fo, pd.core.frame.DataFrame)):
        return cdata
    (R, C) = fo.shape
    if (u'总体' in fo.columns):
        fo.drop([u'总体'], axis=1, inplace=True)
    if any([((u'其他' in ('%s' % s)) or (u'其它' in ('%s' % s))) for s in fo.columns]):
        tmp = [s for s in fo.columns if ((u'其他' in s) or (u'其它' in s))]
        for t in tmp:
            fo.drop([t], axis=1, inplace=True)
    if (u'合计' in fo.index):
        fo.drop([u'合计'], axis=0, inplace=True)
    if any([((u'其他' in ('%s' % s)) or (u'其它' in ('%s' % s))) for s in fo.index]):
        tmp = [s for s in fo.index if ((u'其他' in s) or (u'其它' in s))]
        for t in tmp:
            fo.drop([t], axis=0, inplace=True)
    fe = fo.copy()
    N = fo.sum().sum()
    if (N == 0):
        return cdata
    for i in fe.index:
        for j in fe.columns:
            fe.loc[(i, j)] = ((fe.loc[i, :].sum() * fe.loc[:, j].sum()) / float(N))
    TGI = (fo / fe)
    TWI = (fo - fe)
    CHI = (np.sqrt((((fo - fe) ** 2) / fe)) * ((TWI.applymap((lambda x: int((x > 0)))) * 2) - 1))
    PCHI = (1 / (1 + np.exp(((- 1) * CHI))))
    cdata['FO'] = fo
    cdata['FE'] = fe
    cdata['TGI'] = (TGI * 100)
    cdata['TWI'] = TWI
    cdata['CHI'] = CHI
    cdata['PCHI'] = PCHI
    significant = {}
    significant['threshold'] = stats.chi2.ppf(q=(1 - alpha), df=(C - 1))
    threshold = max(3, min(30, (N * 0.05)))
    ind1 = (fo.sum(axis=1) >= threshold)
    ind2 = (fo.sum() >= threshold)
    fo = fo.loc[(ind1, ind2)]
    if ((fo.shape[0] <= 1) or np.any((fo.sum() == 0)) or np.any((fo.sum(axis=1) == 0))):
        significant['result'] = (- 2)
        significant['pvalue'] = (- 2)
        significant['method'] = 'fo not frequency'
        "fisher_exact运行所需时间极其的长，此处还是不作检验\n        fisher_r,fisher_p=fisher_exact(fo)\n        significant['pvalue']=fisher_p\n        significant['method']='fisher_exact'\n        significant['result']=fisher_r\n        "
    else:
        try:
            chiStats = stats.chi2_contingency(observed=fo)
        except:
            chiStats = (1, np.nan)
        significant['pvalue'] = chiStats[1]
        significant['method'] = 'chi-test'
        if (chiStats[1] <= alpha):
            significant['result'] = 1
        elif np.isnan(chiStats[1]):
            significant['pvalue'] = (- 2)
            significant['result'] = (- 1)
        else:
            significant['result'] = 0
    cdata['significant'] = significant
    chi_sum = (CHI ** 2).sum(axis=1)
    chi_value_fit = stats.chi2.ppf(q=(1 - alpha), df=(C - 1))
    fit_test = chi_sum.map((lambda x: int((x > chi_value_fit))))
    summary = {}
    summary['fit_test'] = fit_test
    summary['chi_std'] = CHI.unstack().std()
    summary['chi_mean'] = CHI.unstack().mean()
    conclusion = ''
    fo_rank = fo.sum().rank(ascending=False)
    for c in fo_rank[(fo_rank < 5)].index:
        tmp = list(CHI.loc[(((CHI[c] - summary['chi_mean']) > summary['chi_std']), c)].sort_values(ascending=False)[:3].index)
        tmp = [('%s' % s) for s in tmp]
        if tmp:
            tmp1 = u'{col}：{s}'.format(col=c, s=' || '.join(tmp))
            conclusion = ((conclusion + tmp1) + '; \n')
    if (significant['result'] == 1):
        if conclusion:
            tmp = '在95%置信水平下显著性检验(卡方检验)结果为*显著*, 且CHI指标在一个标准差外的(即相对有差异的)有：\n'
        else:
            tmp = '在95%置信水平下显著性检验(卡方检验)结果为*显著*，但没有找到相对有差异的配对'
    elif (significant['result'] == 0):
        if conclusion:
            tmp = '在95%置信水平下显著性检验(卡方检验)结果为*不显著*, 但CHI指标在一个标准差外的(即相对有差异的)有：\n'
        else:
            tmp = '在95%置信水平下显著性检验(卡方检验)结果为*不显著*，且没有找到相对有差异的配对'
    elif conclusion:
        tmp = '不满足显著性检验(卡方检验)条件, 但CHI指标在一个标准差外的(即相对有差异的)有：\n'
    else:
        tmp = '不满足显著性检验(卡方检验)条件，且没有找到相对有差异的配对'
    conclusion = (tmp + conclusion)
    summary['summary'] = conclusion
    cdata['summary'] = summary
    return cdata
列联表分析：(观察频数表分析)
# 预增加一个各类别之间的距离
1、生成TGI指数、TWI指数、CHI指数
2、独立性检验
3、当两个变量不显著时，考虑单个之间的显著性
返回字典格式
chi_test: 卡方检验结果，1:显著；0:不显著；-1：期望值不满足条件
coef: 包含chi2、p值、V相关系数
log: 记录一些异常情况
FO: 观察频数
FE: 期望频数
TGI：fo/fe
TWI：fo-fe
CHI：sqrt((fo-fe)(fo/fe-1))*sign(fo-fe)
significant:{
.'result': 显著性结果[1(显著),0(不显著),-1(fe小于5的过多)]
.'pvalue':
.'method': chi_test or fisher_test
.'vcoef':
.'threshold':
}
summary:{
.'summary': 结论提取
.'fit_test': 拟合优度检验
.'chi_std':
.'chi_mean':
def contingency(fo, alpha=0.05):
    " 列联表分析：(观察频数表分析)\n    # 预增加一个各类别之间的距离\n    1、生成TGI指数、TWI指数、CHI指数\n    2、独立性检验\n    3、当两个变量不显著时，考虑单个之间的显著性\n    返回字典格式\n    chi_test: 卡方检验结果，1:显著；0:不显著；-1：期望值不满足条件\n    coef: 包含chi2、p值、V相关系数\n    log: 记录一些异常情况\n    FO: 观察频数\n    FE: 期望频数\n    TGI：fo/fe\n    TWI：fo-fe\n    CHI：sqrt((fo-fe)(fo/fe-1))*sign(fo-fe)\n    significant:{\n    .'result': 显著性结果[1(显著),0(不显著),-1(fe小于5的过多)]\n    .'pvalue':\n    .'method': chi_test or fisher_test\n    .'vcoef':\n    .'threshold':\n    }\n    summary:{\n    .'summary': 结论提取\n    .'fit_test': 拟合优度检验\n    .'chi_std':\n    .'chi_mean':\n    "
    import scipy.stats as stats
    cdata = {}
    if isinstance(fo, pd.core.series.Series):
        fo = pd.DataFrame(fo)
    if (not isinstance(fo, pd.core.frame.DataFrame)):
        return cdata
    (R, C) = fo.shape
    if (u'总体' in fo.columns):
        fo.drop([u'总体'], axis=1, inplace=True)
    if any([((u'其他' in ('%s' % s)) or (u'其它' in ('%s' % s))) for s in fo.columns]):
        tmp = [s for s in fo.columns if ((u'其他' in s) or (u'其它' in s))]
        for t in tmp:
            fo.drop([t], axis=1, inplace=True)
    if (u'合计' in fo.index):
        fo.drop([u'合计'], axis=0, inplace=True)
    if any([((u'其他' in ('%s' % s)) or (u'其它' in ('%s' % s))) for s in fo.index]):
        tmp = [s for s in fo.index if ((u'其他' in s) or (u'其它' in s))]
        for t in tmp:
            fo.drop([t], axis=0, inplace=True)
    fe = fo.copy()
    N = fo.sum().sum()
    if (N == 0):
        return cdata
    for i in fe.index:
        for j in fe.columns:
            fe.loc[(i, j)] = ((fe.loc[i, :].sum() * fe.loc[:, j].sum()) / float(N))
    TGI = (fo / fe)
    TWI = (fo - fe)
    CHI = (np.sqrt((((fo - fe) ** 2) / fe)) * ((TWI.applymap((lambda x: int((x > 0)))) * 2) - 1))
    PCHI = (1 / (1 + np.exp(((- 1) * CHI))))
    cdata['FO'] = fo
    cdata['FE'] = fe
    cdata['TGI'] = (TGI * 100)
    cdata['TWI'] = TWI
    cdata['CHI'] = CHI
    cdata['PCHI'] = PCHI
    significant = {}
    significant['threshold'] = stats.chi2.ppf(q=(1 - alpha), df=(C - 1))
    threshold = max(3, min(30, (N * 0.05)))
    ind1 = (fo.sum(axis=1) >= threshold)
    ind2 = (fo.sum() >= threshold)
    fo = fo.loc[(ind1, ind2)]
    if ((fo.shape[0] <= 1) or np.any((fo.sum() == 0)) or np.any((fo.sum(axis=1) == 0))):
        significant['result'] = (- 2)
        significant['pvalue'] = (- 2)
        significant['method'] = 'fo not frequency'
        "fisher_exact运行所需时间极其的长，此处还是不作检验\n        fisher_r,fisher_p=fisher_exact(fo)\n        significant['pvalue']=fisher_p\n        significant['method']='fisher_exact'\n        significant['result']=fisher_r\n        "
    else:
        try:
            chiStats = stats.chi2_contingency(observed=fo)
        except:
            chiStats = (1, np.nan)
        significant['pvalue'] = chiStats[1]
        significant['method'] = 'chi-test'
        if (chiStats[1] <= alpha):
            significant['result'] = 1
        elif np.isnan(chiStats[1]):
            significant['pvalue'] = (- 2)
            significant['result'] = (- 1)
        else:
            significant['result'] = 0
    cdata['significant'] = significant
    chi_sum = (CHI ** 2).sum(axis=1)
    chi_value_fit = stats.chi2.ppf(q=(1 - alpha), df=(C - 1))
    fit_test = chi_sum.map((lambda x: int((x > chi_value_fit))))
    summary = {}
    summary['fit_test'] = fit_test
    summary['chi_std'] = CHI.unstack().std()
    summary['chi_mean'] = CHI.unstack().mean()
    conclusion = 
    fo_rank = fo.sum().rank(ascending=False)
    for c in fo_rank[(fo_rank < 5)].index:
        tmp = list(CHI.loc[(((CHI[c] - summary['chi_mean']) > summary['chi_std']), c)].sort_values(ascending=False)[:3].index)
        tmp = [('%s' % s) for s in tmp]
        if tmp:
            tmp1 = u'{col}：{s}'.format(col=c, s=' || '.join(tmp))
            conclusion = ((conclusion + tmp1) + '; \n')
    if (significant['result'] == 1):
        if conclusion:
            tmp = '在95%置信水平下显著性检验(卡方检验)结果为*显著*, 且CHI指标在一个标准差外的(即相对有差异的)有：\n'
        else:
            tmp = '在95%置信水平下显著性检验(卡方检验)结果为*显著*，但没有找到相对有差异的配对'
    elif (significant['result'] == 0):
        if conclusion:
            tmp = '在95%置信水平下显著性检验(卡方检验)结果为*不显著*, 但CHI指标在一个标准差外的(即相对有差异的)有：\n'
        else:
            tmp = '在95%置信水平下显著性检验(卡方检验)结果为*不显著*，且没有找到相对有差异的配对'
    elif conclusion:
        tmp = '不满足显著性检验(卡方检验)条件, 但CHI指标在一个标准差外的(即相对有差异的)有：\n'
    else:
        tmp = '不满足显著性检验(卡方检验)条件，且没有找到相对有差异的配对'
    conclusion = (tmp + conclusion)
    summary['summary'] = conclusion
    cdata['summary'] = summary
    return cdata