我是 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/