0

I am generating multidimensional array of different sizes, though they'll all have an even number of columns.

>> import numpy as np
>> x = np.arange(24).reshape((3,8))

Which results in:

array([[ 0,  1,  2,  3,  4,  5,  6,  7],
       [ 8,  9, 10, 11, 12, 13, 14, 15],
       [16, 17, 18, 19, 20, 21, 22, 23]])

I am able to slice with numpy and get the first column in an array:

>> newarr = x[0:,0:2]

array([[ 0,  1],
       [ 8,  9],
       [16, 17]])

However, I want to have one array that is just a list of the columns where column 1 and 2 are together, 3 and 4 are together, and so on.. For example:

array([[[ 0,  1],
       [ 8,  9],
       [16, 17]],
       [[ 2,  3],
       [10, 11],
       [18, 19]],
       etc....]
)

This code below works but it's clunky and my arrays are not all the same. Some arrays have 16 columns, some have 34, some have 50, etc.

>> newarr = [x[0:,0:2]]+[x[0:,2:4]]+[x[0:,4:6]]

[array([[ 0,  1],
       [ 8,  9],
       [16, 17]]), array([[ 2,  3],
       [10, 11],
       [18, 19]])]

There's got to be a better way to do this than

newarr = [x[0:,0:2]]+[x[0:,2:4]]+[x[0:,4:6]]+...+[x[0:,n:n+2]]

Help!

1
  • With numpy slicing there is an option called the step which is formatted as such [start:stop:step]. One example of this is that if you wanted to get every nth column you could do [::n]. This seems relevant to what you are trying to do. Commented Jul 9, 2019 at 21:17

1 Answer 1

1

My idea is adding a for loop:

slice_len = 2
x_list = [x[0:, slice_len*i:slice_len*(i+1)] for i in range(x.shape[1] // slice_len)]

Output:

[array([[ 0,  1],
        [ 8,  9],
        [16, 17]]), array([[ 2,  3],
        [10, 11],
        [18, 19]]), array([[ 4,  5],
        [12, 13],
        [20, 21]]), array([[ 6,  7],
        [14, 15],
        [22, 23]])]
Sign up to request clarification or add additional context in comments.

3 Comments

Perfect! This is exactly what I was trying to do.
@Tuffknitz That's good to be helpful. But you should be careful that when the column size is odd, the number in range should plus one, i.e. range(x.shape[1] // slice_len + 1) so maybe there also need a if ... else....
Thank you for the comments :) I have a check early on in the code that validates this array - if it's an odd number of columns then something is wrong and it will throw an exception.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.