Cupitor
Cupitor

Reputation: 11657

Summing a 1D array with a col of a 2D array

I wonder why this question never came up by somebody else(maybe its so stupid but I need it) and I couldn't figure it out myself. I want to add a 1D array to a specific column or row of a 2D array. The way I did it here sounds really stupid. I don't want to keep the original copy of a in this following example untouched. Is there any other way of doing it?

import numpy as np
a=np.arange(9).reshape((3,3))
b=np.arange(3)
print a 
print b
print a+np.vstack((np.zeros(3),b,np.zeros(3))).T

output:

[[0 1 2]
 [3 4 5]
 [6 7 8]]
[0 1 2]
[[ 0.  1.  2.]
 [ 3.  5.  5.]
 [ 6.  9.  8.]]

EDIT: To keep it fancy, I want to do this in one-liner, since this is a calculation in the middle of evaluating a lambda function! In any case other solutions are very welcomed.

Upvotes: 0

Views: 74

Answers (2)

Saullo G. P. Castro
Saullo G. P. Castro

Reputation: 59005

Is this what you mean?

a[:, 1] += b

print(a)
#array([[0, 1, 2],
#       [3, 5, 5],
#       [6, 9, 8]])

EDIT: to keep the original array untouched:

c = a.copy()
c[:, 1] += b

EDIT2: if you really want an one-liner:

a + np.repeat(b, a.shape[1]).reshape(a.shape)*[0,1,0]

Upvotes: 2

DSM
DSM

Reputation: 353569

How about:

def cadd(arr, slicer, val):
    arr = arr.copy()
    arr[slicer] += val
    return arr

After which:

>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> cadd(a, np.s_[:, 1], b)
array([[0, 1, 2],
       [3, 5, 5],
       [6, 9, 8]])
>>> cadd(a, np.s_[1, :], b)
array([[0, 1, 2],
       [3, 5, 7],
       [6, 7, 8]])
>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

where I've used np.s_ to make a multidimensional slice object conveniently. With enough trickery you could probably make this a one-liner, but why?

Upvotes: 2

Related Questions