laszlopanaflex
laszlopanaflex

Reputation: 1916

operating on two numpy arrays of different shapes

suppose i have 2 numpy arrays as follows:

init = 100
a = np.append(init, np.zeros(5))
b = np.random.randn(5)

so a is of shape (6,) and b is of shape(5,). i would like to add (or perform some other operation, e.g. exponentiation) these together to obtain a new numpy array of shape (6,) whose first value of a (100) is the same and the remaining values are added together (in this case this will just look like appending 100 to b, but that is because it is a toy example initialized with zeroes. attempting to add as is, will produce:

a+b

ValueError: operands could not be broadcast together with shapes (6,) (5,)

is there a one-liner way to use broadcasting, or newaxis here to trick numpy into treating them as compatible shapes?

the desired output:

array([ 100. , 1.93947328, 0.12075821, 1.65319123, -0.29222052, -1.04465838])

Upvotes: 1

Views: 419

Answers (2)

Paul Panzer
Paul Panzer

Reputation: 53029

Not a one-liner but two short lines:

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

Upvotes: 0

ababuji
ababuji

Reputation: 1731

You mean you want to do something like this

np.append(a[0:1], a[1:,] + b)

What do you want your desired output to be? The answer I've provided performs this brodcast add excluding row 1 from a

Upvotes: 2

Related Questions