在Python中随机拆分数组列表

时间:2015-09-05 04:28:15

标签: python arrays numpy random

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

我希望在两个列表中划分(如果可能的话),例如50%

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

或30%和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])]

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

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)

其中使用置换操作以便分区是随机的,并且通过numpy例程明确地完成拆分,以便代码适合一行(尽管这可能不那么重要......)。

输入:

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

输出:

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