1

Hi I have a python code as:

import numpy as np     
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
b = a[0,1]+a[2,2]-a[1,1]
>>> b
>>> 6

Is there any other faster way to add/subtract a list of specific elements of an array?

6
  • Look here: docs.scipy.org/doc/numpy/reference/… Commented Oct 11, 2013 at 7:46
  • 3
    Not sure I understand the question. Is there a faster way to add two specific elements of an array together? No. Is there a faster way to add multiple of elements of an array together? Yes. Can you explain what you are trying to do a bit more? Commented Oct 11, 2013 at 7:57
  • The question is unclear. If you had a series of indices you may use numpy.sum for fast masking and addition on multi-dimensional arrays. Commented Oct 11, 2013 at 8:31
  • @MrE: I need to add and subtract multiple elements of an array together like a[0,1]+a[2,2]-a[1,1] to get some value. Commented Oct 11, 2013 at 8:41
  • 1
    @user2766019 add example/sample data with the series of indices to your question and we can show you how to get the result quickly with NumPy. Commented Oct 11, 2013 at 8:53

1 Answer 1

2

If you simply want to retrieve the values in an array from a list of indices, and sum them, you can do:

import numpy as np
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
ind = [[0,1],[2,2],[1,1]]
values = a[zip(*ind)]
b = values.sum()
# b = 2+9+5 = 16

Note that I set indices ind as a list of indices pairs, and thus zip is necessary. Obviously this can be done in multiple ways. a[...] just needs to get a list or tuple (not numpy array) of indices grouped by axis, i.e. a[(0,2,1),(1,2,1)].

Now to make arbitrary addition or subtraction, there are multiple ways possible. For example:

import numpy as np
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
ind = [[0,1],[2,2],[1,1]]   # indices in array
op = [1,1,-1]               # 1 for addition, -1 for subtraction
values = a[zip(*ind)]*op
b = values.sum()
# b = 2+9-5 = 6

One last point: this method is useful for a set of indices of arbitrary size (i.e. which would be a parameter of your code). For 3 specific values, its is better to do it explicitly as in your code.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.