Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

numpy split array transposed

If I have the following list

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Then

np.array_split([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 3)

Returns

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[array([0, 1, 2, 3]), array([4, 5, 6]), array([7, 8, 9])]

Is there a way to get the sub-arrays in the following order?

[array([0, 3, 6, 9]), array([1, 4, 7]), array([2, 5, 8])]

>Solution :

As the lists are of differing lengths, a numpy.ndarray isn’t possible without a bit of fiddling, as all sub-arrays must be the same length.

However, if a simple list meets your requirement, you can use:

l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
l2 = []

for i in range(3):
    l2.append(l[i::3])

Output:

[[0, 3, 6, 9], [1, 4, 7], [2, 5, 8]]

Or more concisely, giving the same output:

[l[i::3] for i in range(3)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading