Python - 如何使用循环缩短这段重复代码?

标签 python scipy chi-squared

我是 Python 的新手。 以下是我的数据示例:

Category    May  June  July
Product1    32   41    43
Product2    74   65    65
Product3    17   15    18
Product4    14   13    14

我有很多数据集,我想计算每组数据的卡方。 代码如下:

Product1 = [32,41,43]
chi2, p = scipy.stats.chisquare(Product1)
print('Product1')
if p > 0.05:
    print('Same')
else:
    print('Different')

Product2 = [74,65,65]
chi2, p = scipy.stats.chisquare(Product2)
print('Product2')
if p > 0.05:
    print('Same')
else:
    print('Different')

Product3 = [17,15,18]
chi2, p = scipy.stats.chisquare(Product3)
print('Product3')
if p > 0.05:
    print('Same')
else:
    print('Different')

Product4 = [14,13,14]
chi2, p = scipy.stats.chisquare(Product4)
print('Prokduct4')
if p > 0.05:
    print('Same')
else:
    print('Different')

我用“df = pd.read_excel”插入数据表,它自带索引,我不知道如何调用每一行来计算。

如何使用循环并从表中提取数据来缩短这些重复代码? 非常感谢您的帮助。

最佳答案

可以使用循环重复上述步骤,但您也可以利用scipy 处理pandas 数据帧的能力!您可以申请 chisquare使用 axis=1 测试数据帧的所有行。例如:

from scipy.stats import chisquare

df['p'] = chisquare(df[['May', 'June', 'July']], axis=1)[1]

df['same_diff'] = np.where(df['p'] > 0.05, 'same', 'different')

>>> df
   Category  May  June  July         p same_diff
0  Product1   32    41    43  0.411506      same
1  Product2   74    65    65  0.672294      same
2  Product3   17    15    18  0.869358      same
3  Product4   14    13    14  0.975905      same

现在您的数据框将您的 p 值作为一列,以及它们作为一列是“相同”还是“不同”

关于Python - 如何使用循环缩短这段重复代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51561153/

相关文章:

python - 中序二叉树遍历(使用Python)

python - 估计两个时间序列之间的小时间偏移

python - 包括 PyInstaller 的 python 模块?

python - 计算每个数据帧行中的出现次数,然后创建最频繁出现的列

python - 如何比较两个不同列表中字典的键和值并打印不匹配的键和值

python - TCP 和 UNIX 套接字之间有区别吗?

python - 如何使用分类变量进行 scipy 优化

R函数等于excel CHIINV

r - 跨类别和列自动化卡方