【发布时间】:2022-01-23 03:28:35
【问题描述】:
我有一个 numpy 数组(即 x ),其中每行中丢失的列代表索引号。
import numpy as np
import random
np.random.seed(0)
x = np.random.random([5,3])
x = np.append(x, np.arange(x.shape[0]).reshape(-1,1), axis=1)
x=
array([[0.5488135 , 0.71518937, 0.60276338, 0. ],
[0.54488318, 0.4236548 , 0.64589411, 1. ],
[0.43758721, 0.891773 , 0.96366276, 2. ],
[0.38344152, 0.79172504, 0.52889492, 3. ],
[0.56804456, 0.92559664, 0.07103606, 4. ]])
我有另一个 numpy 数组,名为 y,它与第一个数组相关,x 中的每一行在 y 中都有一个用户定义的值相关行。
rep = 4
y = np.random.random([rep*5,3])
array([[0.0871293 , 0.0202184 , 0.83261985],
[0.77815675, 0.87001215, 0.97861834],
[0.79915856, 0.46147936, 0.78052918],
[0.11827443, 0.63992102, 0.14335329],
[0.94466892, 0.52184832, 0.41466194],
[0.26455561, 0.77423369, 0.45615033],
[0.56843395, 0.0187898 , 0.6176355 ],
[0.61209572, 0.616934 , 0.94374808],
[0.6818203 , 0.3595079 , 0.43703195],
[0.6976312 , 0.06022547, 0.66676672],
[0.67063787, 0.21038256, 0.1289263 ],
[0.31542835, 0.36371077, 0.57019677],
[0.43860151, 0.98837384, 0.10204481],
[0.20887676, 0.16130952, 0.65310833],
[0.2532916 , 0.46631077, 0.24442559],
[0.15896958, 0.11037514, 0.65632959],
[0.13818295, 0.19658236, 0.36872517],
[0.82099323, 0.09710128, 0.83794491],
[0.09609841, 0.97645947, 0.4686512 ],
[0.97676109, 0.60484552, 0.73926358]])
例如,x 中的索引 0 与 y 中的索引 0,1,2,3 相关。
假设调用一个方法后,我从数组x的最后一列得到一个索引集。
ind = my_method(x) #Note that it can be any permutation of number 0 to n-1 where n is the number of rows in x
ind
[4, 0] #For the sake of simplicity, let us assume that the method returns [4,0]
我想知道使用给定索引集访问y 行的最有效方法是什么(例如,当有数百万行时)。例如,如果我有ind = [4,0],那么我想在y 中获取行12,13,14,15,0,1,2,3。
预期输出:
[[0.13818295, 0.19658236, 0.36872517],
[0.82099323, 0.09710128, 0.83794491],
[0.09609841, 0.97645947, 0.4686512 ],
[0.97676109, 0.60484552, 0.73926358],
[0.0871293 , 0.0202184 , 0.83261985],
[0.77815675, 0.87001215, 0.97861834],
[0.79915856, 0.46147936, 0.78052918],
[0.11827443, 0.63992102, 0.14335329]]
【问题讨论】:
-
这个问题很难理解。请您提供一个您期望得到的样品吗?也请使用
np.random.seed(0),这样每个人都能得到和你一样的随机值。 -
@richardec 我更新了我的帖子。
-
我的猜测是
np.r_会是一种非常快速的方式:stackoverflow.com/questions/34188620/…