Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/305.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
Python 如何选择numpy数组中的行索引?_Python_Numpy - Fatal编程技术网

Python 如何选择numpy数组中的行索引?

Python 如何选择numpy数组中的行索引?,python,numpy,Python,Numpy,我有以下numpy数组y\u train: KeyError: '[70798 63260 64755 ... 7012 65605 45218] not in index' idx = [np.random.choice(np.where(y_train == i)[0], size=2, \ replace=False) for i in np.unique(y_train)] y_列车= 2 2 1 0 1 1 2 0 0 我需要随机选择n(n=2)行索引,如下所示

我有以下numpy数组
y\u train

KeyError: '[70798 63260 64755 ...  7012 65605 45218] not in index'
idx = [np.random.choice(np.where(y_train == i)[0], size=2, \
       replace=False) for i in np.unique(y_train)]
y_列车=

2
2
1
0
1
1 
2
0
0
我需要随机选择
n
(n=2)行索引,如下所示:

n=2 
n indices of rows where y=0 
n indices of rows where y=1 
n indices of rows where y=2
我使用以下代码:

n=2
idx = [y_train[np.random.choice(np.where(y_train==np.unique(y_train)[I])[0],n)].index.tolist() \
 for i in np.unique(y_train).astype(int)]
我的真实数组中出现错误
y\u train

KeyError: '[70798 63260 64755 ...  7012 65605 45218] not in index'
idx = [np.random.choice(np.where(y_train == i)[0], size=2, \
       replace=False) for i in np.unique(y_train)]

如果您的预期输出是为
y\u序列中的每个唯一值随机选择的索引列表

KeyError: '[70798 63260 64755 ...  7012 65605 45218] not in index'
idx = [np.random.choice(np.where(y_train == i)[0], size=2, \
       replace=False) for i in np.unique(y_train)]
输出:

[array([7, 8]), array([5, 4]), array([1, 0])]
array([7, 8, 5, 4, 1, 0])
如果要将阵列展平为单个阵列:

idx = np.array(idx).flatten()
输出:

[array([7, 8]), array([5, 4]), array([1, 0])]
array([7, 8, 5, 4, 1, 0])

获得所需索引的另一种解决方案是使用
非零
并简单地在
范围(n+1)

您需要在其中输入i==范围(3),然后随机选择(np.where(y_train==i),2,replace=False),然后将索引连接或hstack在一起