1

I have an numpy array:

x = np.zeros(5)
[0,0,0,0,0]

x.put(5)
[0,0,0,0,5]

x.put([1,2,3])
[0,5,1,2,3]

x.put([5,10,10])
[2,3,5,10,10]

I want as shown in the example above. simply I put information at the end. and the data shift and clip the overflow.

samer226047
  • 125
  • 1
  • 13
  • 1
    Any reason you need to use a numpy array instead of a [deque](https://docs.python.org/3/library/collections.html#collections.deque)? – kennytm Mar 12 '17 at 12:13
  • You can create your own object by inheriting from numpy array and just add a custom append method. Here is a similar question http://stackoverflow.com/questions/4151320/efficient-circular-buffer – Mazdak Mar 12 '17 at 12:16
  • 1
    @kennytm yes. because in the end I need a numpy array and this function is executed at least 1 to 2 M times and converting to numpy arrays take considerable computation time – samer226047 Mar 12 '17 at 12:23
  • Note that there exists a function [`ndarray.put`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.put.html), but it does not have the functionality described above. – Leland Hepworth Oct 23 '20 at 16:01

2 Answers2

2

You can copy the tail part of the array to the initial part. Note that this method is O(n), so it is not suitable if the array x is very long.

def push(x, y):
    push_len = len(y)
    assert len(x) >= push_len
    x[:-push_len] = x[push_len:]
    x[-push_len:] = y
    return x
>>> x = numpy.zeros(5)
>>> x
array([ 0.,  0.,  0.,  0.,  0.])
>>> push(x, [5])
array([ 0.,  0.,  0.,  0.,  5.])
>>> push(x, [1,2,3])
array([ 0.,  5.,  1.,  2.,  3.])
>>> push(x, [5,10,10])
array([  2.,   3.,   5.,  10.,  10.])
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
0

Replace the first n values and then roll the array.

x = [0, 1, 2, 3, 4, 5]
y = [6, 7, 8]
indexes = range(0, len(y))
np.put(x, indexes, y)
x
[6, 7, 8, 3, 4, 5]
x = x.roll(len(x) - len(y))
x
[3, 4, 5, 6, 7, 8]