Numpy Slicing: All Except One Array Entry
Solution 1:
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:])
Solution 2:
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
Solution 3:
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).
Solution 4:
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
Solution 5:
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})])
Post a Comment for "Numpy Slicing: All Except One Array Entry"