split array into list of sub lists

Question:

I have a matrix

n  = np.array([2,3,4,5,6,7])

I want to randomly split it to sublists of 2 elements
like this:

new_array = [[2,5] ,[3,4] , [6,7]]

I tried:

s = np.array_split(n, 2)

but this only divide it into 2 sublist not a sublists of two elements )

Asked By: maryam_musalam

||

Answers:

Try:

n = np.array([2, 3, 4, 5, 6, 7])

np.random.shuffle(n)

print(np.array_split(n, n.shape[0] // 2))

Prints:

[array([5, 4]), array([7, 6]), array([2, 3])]
Answered By: Andrej Kesely
ar = np.array([2,3,4,5,6,7])

from numpy.random import default_rng
rng = default_rng()

If you don’t want to modify your original array, here are 2 options:

1.

shuffled = rng.choice(ar, size=len(ar), replace=False)

2.

shuffled = ar.copy()
rng.shuffle(shuffled)

Then just split the shuffled array:

s = np.array_split(shuffled, len(shuffled) // 2)
Answered By: Vladimir Fokow
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.