Reputation: 321
What is the best way to exclude exact one NumPy array entry from an operation?
I have an array x
containing n
values and want to exclude the i
-th entry when I call numpy.prod(x)
. I know about MaskedArray
, but is there another/better way?
Upvotes: 3
Views: 6780
Reputation: 45741
You could use a list comprehension to index all the points but 1:
i = 2
np.prod(x[[val for val in range(len(x)) if val != i]])
or use a set difference:
np.prod(x[list(set(range(len(x)) - {i})])
Upvotes: 0
Reputation: 53029
I think the simplest would be
np.prod(x[:i]) * np.prod(x[i+1:])
This should be fast and also works when you don't want to or can't modify x.
And in case x is multidimensional and i is a tuple:
x_f = x.ravel()
i_f = np.ravel_multi_index(i, x.shape)
np.prod(x_f[:i_f]) * np.prod(x_f[i_f+1:])
Upvotes: 8
Reputation: 151
You could use np.delete
whch removes an element from a one-dimensional array
:
import numpy as np
x = np.arange(1, 5)
i = 2
y = np.prod(np.delete(x, i)) # gives 8
Upvotes: 3
Reputation: 20414
As np.prod
is taking the product of all the elements in an array
, if we want to exclude one element from the solution, we can set that element to 1
first in order to ignore it (as p * 1 = p
).
So:
>>> n = 10
>>> x = np.arange(10)
>>> i = 0
>>> x[i] = 1
>>> np.prod(x)
362880
which, we can see, works:
>>> 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9
362880
Upvotes: 1
Reputation: 1004
I don't think there is any better way, honestly. Even without knowing the NumPy functions, I would do it like:
#I assume x is array of len n
temp = x[i] #where i is the index of the value you don't want to change
x = x * 5
#...do whatever with the array...
x[i] = temp
If I understand correctly, your problem is one dimensional? Even if not, you can do this the same way.
EDIT:
I checked the prod
function and in this case I think you can just replace the value u don't want to use with 1 (using temp
approach I've given you above) and later just put in the right value. It is just a in-place change, so it's kinda efficient. The second way you can do this is just to divide the result by the x[i]
value (assuming it's not 0, as commenters said).
Upvotes: 1