簡體   English   中英

Python-如何通過使用循環使此重復代碼更短?

[英]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=1chisquare檢驗應用於數據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值作為一列,將它們的“相同”或“不同”作為一列

我將數據加載到pandas數據框中后開始:

在此處輸入圖片說明

然后,您可以執行以下操作:

for row in df.iterrows():
    product = row[1][0]
    chi, p = scipy.stats.chisquare(row[1][1:])
    print(product, ":", "same" if p > 0.05 else "different")

這將打印:

Product1 : same
Product2 : same
Product3 : same
Product4 : same

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM