1

i have a list of array in Python

import numpy as np
mylist = [np.random.randint(0, i, int(10)) for i in (10,100,3)]
[array([5, 5, 7, 2, 0, 5, 7, 8, 6, 9]), array([42, 70, 30, 62, 44,  8, 40, 68, 46, 93]), array([0, 0, 0, 0, 0, 1, 2, 0, 1, 2])]

i wish to divide (if possible randomly) for example 50% in two lists

list_one = [array([5, 5, 7, 2, 0]), array([42, 70, 30, 62, 44]), array([0, 0, 0, 0, 0])]
list_two = [array([5, 7, 8, 6, 9]), array([8, 40, 68, 46, 93]), array([1, 2, 0, 1, 2])]

or 30% and 70%

list_one = [array([5, 5, 7]), array([42, 70, 30]), array([0, 0, 0])]
list_two = [array([2, 0, 5, 7, 8, 6, 9]), array([62, 44,  8, 40, 68, 46, 93]), array([0, 0, 1, 2, 0, 1, 2])]
3
  • 1
    So for example you want to randomly select 50% of all the elements of elements and put them in one list and the remainder go in another list? That's simple but tedious. First flatten the list of lists with chain.from_iterable, then for each element run random.uniform(0,1) and if the result is less than .5 put it in the first list else put it in the second list. For 30:70 split make the condition less than .3 for the first list. For less predictable results use random.SystemRandom().random(). Commented Sep 5, 2015 at 4:57
  • Do you want to randomly select a split point (that is, "cut" an array into two), or randomly pick elements (as in Tris Nefzger's comment)? Must the size of the arrays in the resulting lists be the same (i.e., must all elements of list_one be the same length) ? Commented Sep 5, 2015 at 5:11
  • hey guys thanks. I wish or cut (if easier because they are already random numbers) of random pick element if this is not too hard. I am trying right now to find an elegant way to solve this tedious problem Commented Sep 5, 2015 at 5:13

1 Answer 1

2

You can try this:

from numpy.random import permutation
from numpy import split
ratio = 0.3
l1, l2 = zip(*map(lambda x: split(permutation(x), [int(ratio*len(x))]), mylist))
print list(l1)
print list(l2)

where a permutation operation is used so that the partitioning is randomized, and the splitting is explicitly done through a numpy routine so that the code fits in one line (although this may not be that important...).

Input:

[array([3, 3, 7, 0, 0, 6, 6, 6, 6, 0]),
 array([54,  4, 28, 54, 34,  8, 28, 37,  0, 68]),
 array([2, 0, 0, 2, 1, 0, 2, 1, 2, 2])]

Output:

[array([6, 0, 3]), array([37, 54,  8]), array([0, 1, 2])]
[array([0, 7, 6, 3, 6, 0, 6]), array([54, 28,  4, 28, 68,  0, 34]), array([2, 2, 0, 2, 2, 1, 0])]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.