Let's say I have the following array:
a = np.array([[1,2,3,4,5,6],
[7,8,9,10,11,12],
[3,5,6,7,8,9]])
I want to sum the first two values of the first row: 1+2 = 3
, then next two values: 3+4 = 7
, and then 5+6 = 11
, and so on for every row. My desired output is this:
array([[ 3, 7, 11],
[15, 19, 23],
[ 8, 13, 17]])
I have the following solution:
def sum_chunks(x, chunk_size):
rows, cols = x.shape
x = x.reshape(x.size / chunk_size, chunk_size)
return x.sum(axis=1).reshape(rows, cols/chunk_size)
But it feels unnecessarily complicated, is there a better way? Perhaps a built-in?
Method 2: Using the built-in function sum(). Python provides an inbuilt function sum() which sums up the numbers in the list. iterable: iterable can be anything list, tuples or dictionaries, but most importantly it should be numbered.
Method 2: Using the sum() function in NumPy, numpy. sum(arr, axis, dtype, out) function returns the sum of array elements over the specified axis. To compute the sum of all columns the axis argument should be 0 in sum() function.
To add the two arrays together, we will use the numpy. add(arr1,arr2) method. In order to use this method, you have to make sure that the two arrays have the same length. If the lengths of the two arrays are not the same, then broadcast the size of the shorter array by adding zero's at extra indexes.
Just use slicing:
a[:,::2] + a[:,1::2]
This takes the array formed by every even-indexed column (::2
), and adds it to the array formed by every odd-indexed column (1::2
).
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