Let's say I have a numpy array a
containing 10 values. Just an example situation here, although I would like to repeat the same for an array with length 100.
a = np.array([1,2,3,4,5,6,7,8,9,10])
I would like to sum the first 5 values followed by the second 5 values and so on and store them in a new empty list say b
.
So b
would contain b = [15,40]
.
How do I go about doing it?
The numpy. sum() function is available in the NumPy package of Python. This function is used to compute the sum of all elements, the sum of each row, and the sum of each column of a given array. Essentially, this sum ups the elements of an array, takes the elements within a ndarray, and adds them together.
To slice elements from two-dimensional arrays, you need to specify both a row index and a column index as [row_index, column_index] . For example, you can use the index [1,2] to query the element at the second row, third column in precip_2002_2013 .
NumPy sum adds up the values of a NumPy array Essentially, the NumPy sum function sums up the elements of an array. It just takes the elements within a NumPy array (an ndarray object) and adds them together.
Here's (yet) another solution:
In [3]: a.reshape((2,5)).sum(axis=1)
Out[3]: array([15, 40])
Reshape the one-dimensional array to two rows of 5 columns and sum over the columns:
In [4]: a.reshape((2,5))
Out[4]:
array([[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10]])
The sum along each row (summing the column entries) is specified with axis=1
. The reshape happens without copying data (and without modifying the original a
) so it is efficient and fast.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With