[英]Python - How can I make this repetitive code shorter by using loop?
我是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
數據幀的能力! 您可以使用axis=1
將chisquare
檢驗應用於數據chisquare
所有行。 例如:
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
值作為一列,將它們的“相同”或“不同”作為一列
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.