0

I have a rolling window function. It converts a numpy array to list of arrays. However, I want to convert the results of this function to purely array.

import numpy as np

def get_rolling_window(arr, window):
    arr_rolled = [arr[i:i+window] for i in np.arange(arr.shape[0])]
    return arr_rolled

x = np.arange(10).reshape(5,2)
x_rolled = get_rolling_window(x, 2)

now x_rolled is a list of arrays. If I use

x_arr = np.array(x_rolled)

It will not work, because the dtype of x_arr is object, not float or int. And if you

print(x_arr.shape)

you will get (5,). For a pure array of float, its shape should be (5,2,2).

Do you know how to do it?

Thanks

1
  • What does np.concatenate(x_rolled) give you? Commented Mar 14, 2017 at 16:47

1 Answer 1

2

Your x_rolled is a list of arrays of different shapes. So np.array cannot turn it into a multdimensional array of ints.

In [235]: x_rolled
Out[235]: 
[array([[0, 1],
        [2, 3]]), array([[2, 3],
        [4, 5]]), array([[4, 5],
        [6, 7]]), array([[6, 7],
        [8, 9]]), array([[8, 9]])]
In [236]: [x.shape for x in x_rolled]
Out[236]: [(2, 2), (2, 2), (2, 2), (2, 2), (1, 2)]

If I omit the last element, I get a 3d array:

In [237]: np.array(x_rolled[:-1])
Out[237]: 
array([[[0, 1],
        [2, 3]],

       [[2, 3],
        [4, 5]],

       [[4, 5],
        [6, 7]],

       [[6, 7],
        [8, 9]]])
In [238]: _.shape
Out[238]: (4, 2, 2)

which can easily be cast as float

np.array(x_rolled[:-1]).astype(float)

I suspect your roll function is not working as you want.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.