Arrays 选择numpy数组元素
我的任务是在给定的numpy数组中选择p%的元素。比如说,Arrays 选择numpy数组元素,arrays,python-3.x,numpy,Arrays,Python 3.x,Numpy,我的任务是在给定的numpy数组中选择p%的元素。比如说, # Initialize 5 x 3 array- x = np.random.randint(low = -10, high = 10, size = (5, 3)) x ''' array([[-4, -8, 3], [-9, -1, 5], [ 9, 1, 1], [-1, -1, -5], [-1, -4, -1]]) ''' 现在,我想选择p=x中30%的数字
# Initialize 5 x 3 array-
x = np.random.randint(low = -10, high = 10, size = (5, 3))
x
'''
array([[-4, -8, 3],
[-9, -1, 5],
[ 9, 1, 1],
[-1, -1, -5],
[-1, -4, -1]])
'''
现在,我想选择p=x中30%的数字,所以x中30%的数字向上取整为5
有没有办法在x中选择这30%的数字?其中p可以改变,numpy数组x的维数可以是3-D或者更多
我使用的是Python 3.7和numpy 1.18.1
谢谢您可以使用np.random.choice从1d numpy阵列中进行采样,无需更换:
p = 0.3
np.random.choice(x.flatten(), int(x.size * p) , replace=False)
对于大型阵列,不替换采样的性能可能非常差,但也有一些。您可以随机选择0,1并使用NP。非零和布尔索引:
np.random.seed(1)
x[np.nonzero(np.random.choice([1, 0], size=x.shape, p=[0.3,0.7]))]
输出:
array([ 3, -1, 5, 9, -1, -1])
我找到了一种选择p%numpy元素的方法:
p = 20
# To select p% of elements-
x_abs[x_abs < np.percentile(x_abs, p)]
# To select p% of elements and set them to a value (in this case, zero)-
x_abs[x_abs < np.percentile(x_abs, p)] = 0
您希望输出阵列的形状是什么?