Home > Enterprise >  split array into list of sub lists
split array into list of sub lists

Time:08-28

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 )

CodePudding user response:

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])]

CodePudding user response:

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)
  • Related