Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 选择numpy数组元素_Arrays_Python 3.x_Numpy - Fatal编程技术网

Arrays 选择numpy数组元素

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%的数字

我的任务是在给定的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%的数字,所以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

您希望输出阵列的形状是什么?