-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]
Brad
  • 1,360
  • 4
  • 18
  • 27
  • Does this answer your question? [Sum elements in a row (Python/Numpy)](https://stackoverflow.com/questions/30387280/sum-elements-in-a-row-python-numpy) – Pranav Hosangadi Feb 13 '23 at 22:45
  • Linking a similar question with a dissimilar answer is not helpful – Brad Feb 14 '23 at 00: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? – Pranav Hosangadi Feb 14 '23 at 00: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. – Brad Feb 14 '23 at 00:39
  • Ah, then the duplicate for this question is [How to add two columns of a numpy array?](https://stackoverflow.com/questions/13735608/how-to-add-two-columns-of-a-numpy-array). – Pranav Hosangadi Feb 14 '23 at 01:07

1 Answers1

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]
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
  • 1
    Does something speak against `ary[:, 0] += ary[:, 1]`? – Kelly Bundy Feb 13 '23 at 23:01
  • 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 Feb 14 '23 at 00:26
  • @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 – Pranav Hosangadi Feb 14 '23 at 01:09