-1

I am trying to extract first and last element from array "x" and then repeat for five times then finally concatenate to original "x".

Error: operands cannot be broadcast together with shapes (5,) (1000,)

Here is the code

import numpy as np 
import random
x= np.random.uniform(0, 1, 1000)
x = [x[0]]*5 + x + [x[-1]]*5
  • What are you trying to do? In numpy, addition is applied to each member of the two arrays and so they have to be the same size. `[x[0]]*5` is a 5 element array. What is `x[5]` supposed to be added to? Are you interesting in appending the arrays? That's what you happen if you were using regular python arrays. – tdelaney Feb 22 '20 at 18:34
  • Does this answer your question? [python numpy ValueError: operands could not be broadcast together with shapes](https://stackoverflow.com/questions/24560298/python-numpy-valueerror-operands-could-not-be-broadcast-together-with-shapes) – AMC Feb 22 '20 at 18:51
  • Those aren't lists, those are NumPy ndarrays. – AMC Feb 22 '20 at 18:51

1 Answers1

0

It is not clear what you are tying to achieve. There are not really two lists in your example.

It seems like you're trying to do one of these two things:

  • Add the first and last element (times 5) to all elements of the array
  • Add the value of the previous and next elements (times 5) to each element

For the first objective, you would only be adding scalars to the array so you must not enclose the first/last items in aquare brackets:

    import numpy as np 
x= np.random.uniform(0, 1, 1000)
x = x[0]*5 + x + x[-1]*5

for the second objective, you could do it using assignments to a copy of the array:

y = x.copy()
y[:-1] += 5*x[1:]
y[1:]  += 5*x[:-1]

[EDIT] based on the OP's comment, he needs padding of 5 on each side. the np.pad() function can do it directly:

x = np.pad(x,(5,5),mode="edge")

example:

a = np.array([7,8,9])
np.pad(a,(5,5),mode="edge")

# array([7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 9, 9, 9])
Alain T.
  • 40,517
  • 4
  • 31
  • 51
  • x = [0,10,5,3,1,5] ; x = [x[0]]*2 + x + [x[-1]]*2 ; give output as [0, 0, 0, 10, 5, 3, 1, 5, 5, 5]………..………….This is what I want from above code – Bimlendra Ray Feb 23 '20 at 03:45