Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python numpy array sum over certain indices

How to perform a sum just for a list of indices over numpy array, e.g., if I have an array a = [1,2,3,4] and a list of indices to sum, indices = [0, 2] and I want a fast operation to give me the answer 4 because the value for summing value at index 0 and index 2 in a is 4

like image 1000
Marcus_Ma Avatar asked Dec 09 '17 23:12

Marcus_Ma


People also ask

How to sum a NumPy array in Python?

How to sum a numpy array? 1 # arr is a numpy array. 2 # sum of all values arr.sum() 3 # sum of each row (for 2D array) arr.sum(axis=1) 4 # sum of each column (for 2D array) arr.sum(axis=0) 5 # sum along a specific axis, n arr.sum(axis=n) You can also specify the axis to sum the numpy array along with the axis parameter (see the examples ...

How to sum an array of indices in Python?

The accepted a [indices].sum () approach copies data and creates a new array, which might cause problem if the array is large. np.sum actually has an argument to mask out colums, you can just do Which doesn't copy any data. >>> a = [1,2,3,4] >>> indices = [0, 2] >>> sum (a [i] for i in indices) 4

How do you Index an array in NumPy?

Array indexing is the same as accessing an array element. You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc. Get the second element from the following array.

How do you sum values along an axis in Python?

When we use np.sum with the axis parameter, the function will sum the values along a particular axis. In particular, when we use np.sum with axis = 0, the function will sum over the 0th axis (the rows). It’s basically summing up the values row-wise, and producing a new array (with lower dimensions).


3 Answers

The accepted a[indices].sum() approach copies data and creates a new array, which might cause problem if the array is large. np.sum actually has an argument to mask out colums, you can just do

np.sum(a, where=[True, False, True, False])

Which doesn't copy any data.

The mask array can be obtained by:

mask = np.full(4, False)
mask[np.array([0,2])] = True
like image 125
Tong Zhou Avatar answered Oct 07 '22 15:10

Tong Zhou


You can use sum directly after indexing with indices:

a = np.array([1,2,3,4])
indices = [0, 2] 
a[indices].sum()
like image 21
andrew_reece Avatar answered Oct 07 '22 17:10

andrew_reece


Try:

>>> a = [1,2,3,4]
>>> indices = [0, 2]
>>> sum(a[i] for i in indices)
4

Faster

If you have a lot of numbers and you want high speed, then you need to use numpy:

>>> import numpy as np
>>> a = np.array([1,2,3,4])
>>> a[indices]
array([1, 3])
>>> np.sum(a[indices])
4
like image 3
John1024 Avatar answered Oct 07 '22 15:10

John1024