简体   繁体   English

Numpy 如何将二维数组的元素相加?

[英]How is Numpy sum adding up elements of a 2d array?

Say I have a numpy 2D array:假设我有一个 numpy 二维数组:

>>> t
array([[-0.00880717,  0.02522217, -0.01014062],
       [-0.00866732,  0.01737254,  0.05396272]])

Now using array slicing, I can quickly obtain all items in all rows starting from the column with index 1 and sum them up:现在使用数组切片,我可以快速获取从索引为1的列开始的所有行中的所有项目并将它们相加:

>>> t[:, 1:].sum()
0.08641680780899146

To verify manually, here is what happens:要手动验证,会发生以下情况:

>>> 0.02522217+0.01737254+-0.01014062+0.05396272
0.08641680999999998

Just to understand the numpy array operations better, is numpy first going over all rows and summing the items of the rows, or is it going down one column, and then down the next one?只是为了更好地理解 numpy 数组操作,numpy 是先遍历所有行并对行的项目求和,还是先向下一列,然后向下一列?

Thanks for asking your question, @TMOTTM!感谢您提出问题,@TMOTTM!

The way NumPy's sum semantics work are documented in theNumPy manual . NumPy 求和语义的工作方式记录在NumPy 手册中。

To summarize the manual while injecting my own understanding:总结一下手册,同时注入我自己的理解:

  1. arr.sum() called without an axis argument simply sums up everything in the array. arr.sum()在没有axis参数的情况下调用只是简单地总结了数组中的所有内容。 It is the most straightforward semantic operation to implement.这是实现的最直接的语义操作。
  2. arr.sum(axis=0) will collapse axis 0 (the first axis) while summing. arr.sum(axis=0)将在求和时折叠轴 0(第一个轴)。
  3. arr.sum(axis=k) will collapse axis k while performing a summation. arr.sum(axis=k)将在执行求和时折叠轴k

Canonically, axis 0 is semantically recognized as the row-wise axis, axis 1 is the column-wise axis, and axis 2 is the depth-wise axis, and anything higher goes into hypercubes which are not easily described in words.典型地,轴0在语义上被识别为行轴,轴1是列轴,轴2是深度轴,任何更高的都进入超立方体,不容易用语言描述。

Made concrete:混凝土:

  1. In a 2D array, to collapse the rows (ie sum column-wise), do arr.sum(axis=0) .在二维数组中,要折叠行(即按列求和),请执行arr.sum(axis=0)
  2. In a 2D array, to collapse the columns (ie sum row-wise), do arr.sum(axis=1) .在二维数组中,要折叠列(即按行求和),请执行arr.sum(axis=1)

At the end of the day, point 3 is the one you want to remember: reason carefully about which axis you wish to collapse, and you'll never go wrong!归根结底,第 3 点是您要记住的:仔细推理您希望折叠哪个轴,您永远不会错!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM