0

I want to implement a rolling concatenation function for numpy array of arrays. For example, if my numpy array is the following:

 [[1.0]
  [1.5]
  [1.6]
  [1.8]
  ...
  ...
  [1.2]
  [1.3]
  [1.5]]

then, for a window size of 3, my function should return:

 [[1.0]
  [1.0 1.5]
  [1.0 1.5 1.6]
  [1.5 1.6 1.8]
  ...
  ...
  [1.2 1.3 1.5]]

The input array could have elements of different shapes as well. For example, if input is:

[[1.0]
 [1.5]
 [1.6 1.7]
 [1.8]
 ...
 ...
 [1.2]
 [1.3]
 [1.5]]

then output should be:

 [[1.0]
  [1.0 1.5]
  [1.0 1.5 1.6 1.7]
  [1.5 1.6 1.7 1.8]
  ...
  ...
  [1.2 1.3 1.5]]
6
  • The input doesn't look like an array. Commented Apr 11, 2017 at 10:24
  • edited question Commented Apr 11, 2017 at 10:32
  • If you are willing to pad with NaNs/some-other-invalid-specifier to keep a 2D shaped array, take a look here - stackoverflow.com/questions/40683601/… Commented Apr 11, 2017 at 10:33
  • 1
    This isn't really a numpy question, it looks more like a list concatenation. You're starting and finishing with a ragged list, which means there's nothing in numpy that will make your life easier. Commented Apr 11, 2017 at 10:52
  • @DanielForsman all those individual elements are actually numpy arrays and not lists. the overall structure is an array of arrays Commented Apr 11, 2017 at 11:11

1 Answer 1

1

First, make your array into a list. There's no purpose in having an array of arrays in numpy.

l = arr.tolist()           #l is a list of arrays

Now use list comprehension to get your elements, and concatenate them with np.r_

l2 = [np.r_[tuple(l[max(i - n, 0):i])] for i in range(1, len(l)+1)]
Sign up to request clarification or add additional context in comments.

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.