I am trying to split an numpy.array
of length 40 into smaller, equal-sized numpy.array
s, in which the number of the smaller arrays is given by the user. It is allowed to have some overlap between the smaller arrays, as situations can occur where the full length is only divisible by the splits given some form of overlap of the smaller arrays.
If I had an array np.array([range(40)])
And I had to split it into 37 sub arrays, the list of subarrays should be like this:
[1, 2, 3], [3, 4, 5], [5, 6, 7], ... [38, 39, 40]
I tried using numpy.split
but this only works when the length is divisible by the size, and numpy.array_split
generates uneven sizes.
Example using numpy.split
>> import numpy as np
>>> a = np.random.randint(6,size=(40))
>>> b = np.split(a,37)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/site-packages/numpy/lib/shape_base.py", line 508, in split
'array split does not result in an equal division')
ValueError: array split does not result in an equal division
And with numpy.array_split
>>> a = np.random.randint(5,size=(40))
>>> b = np.array_split(a,37)
>>> print len(b)
37
>>> print b[0].shape
(2,)
>>> print b[3].shape
(1,)
>>> print b[5].shape
(1,)
>>> print b[6].shape
(1,)
>>> print b[30].shape
(1,)
>>>
numpy.array_split
don't equally divide them.
Any solution?
To divide an array into two, we need at least three array variables. We shall take an array with continuous numbers and then shall store the values of it into two different variables based on even and odd values.
An efficient solution is to first find the sum S of all array elements. Check if this sum is divisible by 3 or not. This is because if sum is not divisible then the sum cannot be split in three equal sum sets. If there are three contiguous subarrays with equal sum, then sum of each subarray is S/3.
What you're describing is called a (sliding) window, not a split.
See this answer: https://stackoverflow.com/a/15722507/7802200
What you want is to use the window_stack
function developed there with a width
of len(a) - n_splits + 1
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With