-1

How do I vectorize addition between columns in a numpy array? For example, what is the fastest way to implement something like:

import numpy

ary = numpy.array([[1,2,3],[3,4,5],[5,6,7],[7,8,9],[9,10,11]])
for i in range(ary.shape[0]):
    ary[i,0] += ary[i,1]
5
  • Does this answer your question? Sum elements in a row (Python/Numpy) Commented Feb 13, 2023 at 22:45
  • Linking a similar question with a dissimilar answer is not helpful Commented Feb 14, 2023 at 0:20
  • I'm not sure I understand the problem -- you asked how to get the rowwise sum of a numpy array. The link above shows you how to do that (sure, it may not answer your exact question, but it does answer the question you seem to be asking). If you were actually asking a different question, please clarify. Are you asking how to add only the first two columns? Commented Feb 14, 2023 at 0:24
  • The slicing operator in RomanPerekhrest's answer is not in the linked question. I realize ary.sum works for only 2 columns like my original example, I revised my question to include an additional column. Commented Feb 14, 2023 at 0:39
  • Ah, then the duplicate for this question is How to add two columns of a numpy array?. Commented Feb 14, 2023 at 1:07

1 Answer 1

2

With numpy.ndarray.sum over axis 1:

ary[:,0] = ary.sum(axis=1)

Or the same with straightforward addition on slices:

ary[:,0] = ary[:, 0] + ary[:, 1]
Sign up to request clarification or add additional context in comments.

3 Comments

Does something speak against ary[:, 0] += ary[:, 1]?
The slicing operator is the syntax I was looking for, however I am curious if ary.sum is faster, and if it can be used to add the 1st and 2nd column in cases where there are more than 2 columns and I don't want the 3rd and subsequent columns included in the sum.
@Brad sum(axis=1) is applied over the entire array, so if you only want to sum two columns you could slice those columns first e.g. ary[:, :2].sum(axis=1) will select only the first two columns, and then apply sum(axis=1) to that slice

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.