Home > Software engineering >  splitting array into 3 arrays
splitting array into 3 arrays

Time:09-16

Note: please edit the title to be more reflective of the question; I could not come up with a way to phrase it.

I have very large array; here is some sample data:

array([ 0.2952941 -0.22235294j, -0.4027451  0.2090196j ,
       -0.19882353 0.2717647j ,  0.17764705-0.1282353j ,
        0.38156864-0.23803921j,  0.25607842-0.28509805j,
       -0.4262745  0.42078432j, -0.33215687 0.17764705j,
       -0.23019607 0.19333333j], dtype=complex64)

How can I split it into three numpy array's, such that:

a = [0.2952941 -0.22235294j, 0.17764705-0.1282353j, -0.4262745  0.42078432j]
b = [-0.4027451  0.2090196j, 0.38156864-0.23803921j, -0.33215687 0.17764705j]
c = [-0.19882353 0.2717647j, 0.25607842-0.28509805j, -0.23019607 0.19333333j]

As you can see, the 1st, 4th, 7th are in a. The 2nd, 5th and 8th are in b. And the 3rd, 6th, and 9th are in c

CodePudding user response:

If you know the shape of the array is a multiple of 3, you can reshape it into rows of 3 and transpose. This will give you the rows you want, which you can unpack if you choose to.

import numpy as np

a = np.array([ 
       0.2952941 -0.22235294j, -0.4027451  0.2090196j ,
       -0.19882353 0.2717647j ,  0.17764705-0.1282353j ,
        0.38156864-0.23803921j,  0.25607842-0.28509805j,
       -0.4262745  0.42078432j, -0.33215687 0.17764705j,
       -0.23019607 0.19333333j], dtype=np.complex64)

a, b, c = a.reshape(-1, 3).T

This will give a, b, c:

array([ 0.2952941 -0.22235294j,  0.17764705-0.1282353j ,
        -0.4262745  0.42078432j], dtype=complex64),
array([-0.4027451  0.2090196j ,  0.38156864-0.23803921j,
        -0.33215687 0.17764705j], dtype=complex64),
array([-0.19882353 0.2717647j ,  0.25607842-0.28509805j,
        -0.23019607 0.19333333j], dtype=complex64)

CodePudding user response:

To split array into sub-array, numpy already provide the function. for your case you can use like this

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
a, b, c = np.array_split(arr, 3)

a
>> array([1, 2, 3])

b
>> array([4, 5, 6])

c
>> array([7, 8, 9])

3 in np.array_split is the number of how many you want to split the array.

Hope it helps

  • Related