使用python从给定矩阵中随机选择特征

时间:2018-09-05 14:33:28

标签: python matrix random

我有一个使用python创建的6 x 6矩阵。从矩阵中包含的36个值中,我想从矩阵中选择非零的任何10个值(它应该随机选择值,而不是通过指定位置),并且应该在最后打印所选的10个值。请帮我处理python中的代码

 import numpy as np
 from numpy import random
 #import Dataframe.sample as df 
 rows = 6
 cols = 6 
 a = np.matrix(np.random.randint(220,376, size=(rows,cols)))
 print (a)

2 个答案:

答案 0 :(得分:1)

考虑6x6矩阵:

x = np.arange(36).reshape(6,6)

然后您可以在折叠成一维(random.choice())的矩阵上使用flatten()

np.random.choice(x.flatten(), 10, replace=False)

获得10个随机元素。


对于np.matrix,就像您的情况一样,它会更改,我不知道直接方法。您可以做如下。 您选择索引。

selected = np.random.choice(a.shape[0]*a.shape[1], 10, replace=False)
# e.g., array([[25, 19,  5,  4, 32, 33, 13,  1,  2, 16]]) 
# a.shape[0]*a.shape[1]=36 in your case

最后,在flatten()矩阵上获取与选定索引对应的元素

a.flatten()[0,selected]

修改

还有一种基于numpy.matrix.A1

的直接方法
a = np.matrix(np.random.randint(220,376, size=(6,6)))
elements = np.random.choice(a.A1, 10, replace=False)

答案 1 :(得分:0)

您可以使用matrix[y][x]访问矩阵,并使用随机包生成随机索引。随机可以与import random一起使用。导入后,您可以使用x = random.randint(0,5)生成随机索引。

一个简短的例子:

import random
for i in range(10): #10 times
    x = random.randint(0,5) #index X
    y = random.randint(0,5) #index Y
    value = matrix[y][x] #get the value
    print(value) #print the value

请注意,我的矩阵的名称为matrix,您的矩阵名为a