python - How can I add all the elements of a Matrix using numpy?
问题描述
I have a function called check_sum that adds all the elements of an 2d array.
Grid is a 2d array, and grid_shape is 1024x1024.
I'm trying to use the numpy.matrix.sum function, but after several attempts I don't know how to implement it, it always gives me another value.
def check_sum(grid):
xmax, ymax = grid_shape
s=0
for i in range(xmax):
for j in range(ymax):
s += grid[i][j]
return s
解决方案
您可以调用grid.sum()
它,它将返回数组中所有条目的总和,无论它是 2d 数组还是 3d 数组。Sum()
是一种通用的 numpy 方法,它适用于矩阵和数组。这里
推荐阅读
- javascript - Vue 组件中的 props 是可变的吗?
- tesseract - 当前版本的 pytesseract 产生错误的字符串
- r - 如何在同一单元格中包含百分比和分子/分母
- database - 使用golang程序同时连接两个TDengine节点,查询数据混乱
- azure-sql-database - 是否应该在数据仓库中自动(每天)刷新所有数据源?(天蓝色)
- reactjs - 错误:useForm 必须在 a 内使用
- python - 优化 Lifetime 的 BG/NBD fitter 的执行
- dart - 将 EPOC 时间戳转换为 DateTime?在 json_serializable
- css - react-bootstrap css 覆盖自定义 css
- php - 将值附加到多选时,jquery重复项目