1

I have been trying to split a n dimensional array. I want to split it at multiples of 100//3 (=33)

I want to split array of length 100 into 3 groups such that group 1 is from indices 0-33 group 2 is from 34-66 group 3 is from 67-100

This is what I tried.

numberblocks=3
array=np.arange(17)
splitat=len(array)//3
for i in range(1,numberblocks):
    np.split(array, splitat*i)

However this is not producing any output. Is there anything wrong in this logic? How do I achieve this.?

1 Answers1

2

You can just use:

np.array_split(array, n)

to split the array array into n equal parts if possible, and if not the last split will be smaller than the rest.

In your case,

>>> array = np.arange(100)
>>> split_arrs = np.array_split(array, 3)
>>> split_arrs
[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, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]), array([34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
   51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66]), array([67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
   84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99])]
>>> split_arrs[0]
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, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33])
>>> split_arrs[1]
array([34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
   51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66])
>>> split_arrs[2]
array([67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
   84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99])
GoodDeeds
  • 7,956
  • 5
  • 34
  • 61
  • How do I save these to do the further operation? – NewbietoPython Mar 08 '20 at 19:16
  • @NewbietoPython You can simply assign it to a new object, it will then hold a list of arrays. (e.g., `newarr = np.array_split(array, 3)`) – GoodDeeds Mar 08 '20 at 19:17
  • But I what i meant is I have to split it at indices which are muplies of 3. I want to split the array of length 100 into 3 groups such that group 1 is from indices 0-33 group 2 is from 34-66 group 3 is from 67-100 @GoodDeeds – NewbietoPython Mar 08 '20 at 19:21
  • @NewbietoPython So for arr = [1,2,3,4,5,6], you want to split it into a1 = [1,4], a2 = [2,5], and a3 = [3,6]? That's not clear from your question, as you say "I want to split array of length 100 into 3 groups such that group 1 is from indices 0-33 group 2 is from 34-66 group 3 is from 67-100". So I assumed you wanted a1 = [1,2], a2 = [3,4], and a3 = [5,6]. Please clarify. – GoodDeeds Mar 08 '20 at 19:23
  • @NewbietoPython I don't understand, doesn't this answer do exactly as you want? Please see updated example. – GoodDeeds Mar 08 '20 at 19:28
  • My bad! You are right. I have accepted your answer. I am not able to upvoat ur answer as i dont have enough reputation – NewbietoPython Mar 08 '20 at 19:37