[英]Create chi2 array of 2d array
我正在使用下面的循環來創建一個包含每個單元格 chi2 的第三個數組。
所以我在下面做的是: <data's column total of col 0>
與<total percentage's first 0>
並將其添加到<chiSqrArray's 0:0>
並繼續相應的位置,直到循環用完。
data = array([[34, 14],
[52, 27],
[15, 52],
[13, 11]])
total_percentages = array([0.22018349, 0.36238532, 0.30733945, 0.11009174]) #the percentages of total for each row
col_total = np.sum(data, axis=0)
Tcolumn = 0
chiSqrArray = []
for c in data.transpose():
row_count = 0
r = []
for cell in c:
chiSqr = col_total[Tcolumn] * total_percentages[row_count]
r.append(round(chiSqr, 2))
row_count += 1
chiSqrArray.append(r)
Tcolumn += 1
exp = np.array(chiSqrArray).transpose()
>>> array([[25.1 , 22.9 ],
[41.31, 37.69],
[35.04, 31.96],
[12.55, 11.45]])
它工作得很好......但是 numpy beg numpy:我認為必須有一種更有效/更簡潔的方法來創建這個 chiSqr 數組?
我不知道這是否有特殊的 function 但您可以更簡單地編寫代碼
chiSqrArray = []
for total in col_total:
row = total * total_percentages
row = np.around(row, 2)
chiSqrArray.append(row)
exp = np.array(chiSqrArray).T
如果在創建數組后對其進行舍入
chiSqrArray = [total * total_percentages for total in col_total]
exp = np.array(chiSqrArray).T
exp = np.around(exp, 2)
最少的工作代碼
import numpy as np
data = np.array([
[34, 14],
[52, 27],
[15, 52],
[13, 11]
])
total_percentages = np.array([0.22018349, 0.36238532, 0.30733945, 0.11009174])
col_total = np.sum(data, axis=0)
chiSqrArray = [total * total_percentages for total in col_total]
exp = np.array(chiSqrArray).T
exp = np.around(exp, 2)
print(exp)
編輯:我在上面的評論中檢查了@WarrenWeckesser 的建議,這可以是
import numpy as np
from scipy.stats import chi2_contingency
data = np.array([
[34, 14],
[52, 27],
[15, 52],
[13, 11]
])
exp = chi2_contingency(data)[3]
#_, _, _, exp = chi2_contingency(data)
exp = np.around(exp, 2)
print(exp)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.