Home > Enterprise >  create sub-arrays of an array with numpy
create sub-arrays of an array with numpy

Time:01-19

Let's say I have a numpy array :

a = np.array([10,11,12,13,22,23,24,25,30,31,32,33,34])

I would like to create sub-arrays which contain elements for which the difference is equal to 1
I tried to look for indices where the difference is greater than 1 with

c = np.where(a[1:]-a[:-1]>1)

In this case the result will be

array1=np.array([10,11,12])
array2=np.array([22,23,24,25])
array3=np.array([30,31,32,33,34])

But I do not know how to do that because the number of sub-arrays can change
Any idea ?

CodePudding user response:

Try this:

diff_1 = ~(np.diff(a)==1)
ids = np.arange(len(diff_1))[diff_1] 1
result = np.split(a, ids, axis=0)

CodePudding user response:

If you want your subarrays you just have to use the indexes returned by np.where & store the subarrays within those indexes in a list:

a = np.array([4,5,10,11,12,13,22,23,24,25,30,31,32,33,34])
c = np.where(a[1:]-a[:-1]>1)
li=[]
start=0
end=len(a)
for i in c[0]:
    li.append(a[start:i 1])
    start=i 1
li.append(a[start:end])
  •  Tags:  
  • Related