Home > OS >  How can I split a numpy array into equal elements each in python? The last element of each array wil
How can I split a numpy array into equal elements each in python? The last element of each array wil

Time:12-09

I want to split an array of 14 elements into 4 equal elements. For example The input array:my_array[1,2,3,4,5,6,7,8,9,10,11,12,13,14] I want to split array my_array like this: my_array[1,2,3,4],[2,3,4,5],[3,4,5,6],[4,5,6,7],......,[11,12,13,14]

Can any of you explain how to do this? (I am working on python using numpy, also It would be nice if your answers are related to numpy.)

I tried basic split functions on numpy.

import numpy as np 

my_array = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14]
np.array_split(my_array,4)

[array([1, 2, 3, 4]),
 array([5, 6, 7, 8]),
 array([ 9, 10, 11]),
 array([12, 13, 14])]

CodePudding user response:

Well, as of the output you described, every other array starts with the 2nd element of the previous array. You don't need especially numpy to split them evenly, you can achieve it by looping over elements, but you won't be able to make only 4 arrays trying to split them evenly.

my_list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14]

output_list = []
for i in my_list[:-3]:
    new_list = []
    for j in range(4):
        new_list.append(my_list[j i-1])

    output_list.append(tuple(new_list))

print(output_list) 

This method however, will give you one long list:

    [(1, 2, 3, 4), (2, 3, 4, 5), (3, 4, 5, 6), (4, 5, 6, 7), (5, 6, 7, 8), 
     (6, 7, 8, 9), (7, 8, 9, 10), (8, 9, 10, 11), (9, 10, 11, 12),
     (10, 11, 12, 13), (11, 12, 13, 14)]

CodePudding user response:

By documentation of numpy.lib.stride_tricks.sliding_window_view you could create a sliding window view into the array that slides across all the array and extracts subsets of the array at all window positions:

import numpy as np
my_array = np.arange(1, 15)
np.lib.stride_tricks.sliding_window_view(my_array, 4)

>>> array([[ 1,  2,  3,  4],
       [ 2,  3,  4,  5],
       [ 3,  4,  5,  6],
       [ 4,  5,  6,  7],
       [ 5,  6,  7,  8],
       [ 6,  7,  8,  9],
       [ 7,  8,  9, 10],
       [ 8,  9, 10, 11],
       [ 9, 10, 11, 12],
       [10, 11, 12, 13],
       [11, 12, 13, 14]])

Note that np.__version__ >= '1.20.0' is required. sliding_window_view method is a substitute for less safe routine numpy.lib.stride_tricks.as_strided of older versions:

wsize = 4
np.lib.stride_tricks.as_strided(my_array, 
                                shape=(len(my_array) - wsize   1, wsize), 
                                strides=(my_array.itemsize, my_array.itemsize))

There are also some great explanations how it works on StackOverlow

  • Related