1

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])

2
  • 1
    Could you do numpy.random.seed(0) at the top and re run your code and re print your desired output? Because np.random created random values. And your random values will be different from when I call np.random from my console. Commented Oct 6, 2018 at 1:36
  • Could you tell me if my answer gives you your desired output? Commented Oct 6, 2018 at 1:40

2 Answers 2

2

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

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

2 Comments

this works, but perhaps this is sufficient: np.append(a[0], a[1:] + b)
Feel free to upvote and accept if my solution works.. Yeah they basically do the same thing
0

Not a one-liner but two short lines:

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

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.