使用python从给定矩阵中随机选择要素

问题描述 投票:-1回答:2

我有一个使用python创建的6乘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)
python matrix random
2个回答
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)

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

© www.soinside.com 2019 - 2024. All rights reserved.