python - 创建二维数组的 chi2 数组
问题描述
我正在使用下面的循环来创建一个包含每个单元格 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 数组?
解决方案
我不知道这是否有特殊功能,但您可以更简单地编写代码
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)
推荐阅读
- c - 我如何不让我的总和加上第一个总和?
- python - python pandas TypeError:int对象不可调用
- excel - 跨另一个工作簿工作表的 Excel VBA 查找
- go - 将字符串解析为 net.Addr
- java - Java 应用程序的配置文件
- node.js - jest 和 npm 没有运行测试,只是挂起
- php - PHP 语法,是 $this->(stuff) ->(more stuff) 和 $this->(stuff); 一样 $this->(更多东西)?
- javascript - 不要使用 React-Select 清除选择时的输入
- java - spring cache - 如果更新逻辑失败,如何恢复到原始缓存?- @cacheable @cacheput @cacheevict
- javascript - javascript中通用模板文字函数的标记