python从数组中随机选择⼀部分取出,并从原数组中删除取出的内容可以使⽤numpy中的random.choice函数随机选择数组的下标
numpy.random.choice(a, size=None, replace=True, p=None)
#a为⼀维数组或int值,为⼀维数组时会从该数组中随机选择元素,为int值时会先⽣成⼀个np.arange(a)的数组,然后从中随机选择元素#size为int值,为选择元素的个数
#replace默认为True,意思是随机选择出的元素还会放回样本集中,即⽣成的数列中可能存在相同的元素,为False时就不会出现
#p为样本选择的概率,默认为⼀致分布
import numpy as np
data=np.random.random(size=10)
data
Out[4]:
array([ 0.21575642,  0.30620622,  0.01454852,  0.46253994,  0.11222712,
0.32893411,  0.11040516,  0.51010326,  0.83162364,  0.84285834])
index_1=np.random.choice(data.shape[0],4,replace=False)
index_1
random python
Out[6]: array([1, 4, 2, 3])
data1=data[index_1]
data1
Out[8]: array([ 0.30620622,  0.11222712,  0.01454852,  0.46253994])
然后我们如何获得剩下的数组中的内容呢,我们可以先⽣成原数组所有的下标,然后⽤np.delete函数删除之前随机⽣成的下标数组
numpy.delete(arr,obj,axis=None)
#arr:输⼊向量
#obj:表明哪⼀个⼦向量应该被移除。可以为整数或⼀个int型的向量
#axis:表明删除哪个轴的⼦向量,若默认,则返回⼀个被拉平的向量
index_2=np.arange(data.shape[0])
index_2
Out[10]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
index_2=np.delete(index_2,index_1)
index_2
Out[12]: array([0, 5, 6, 7, 8, 9])
data2=data[index_2]
data2
Out[14]:
array([ 0.21575642,  0.32893411,  0.11040516,  0.51010326,  0.83162364,
0.84285834])