我有一个数组x,argsorting的结果为i.我需要根据ix(和y,这里无关紧要)进行数百次排序.因此,对数据进行两次排序是不可能的,一切都需要通过初始排序i来实现. 如果我取x[i],它会像预期那样返回排序后的x.然而,我现在只想通过n使用某些行(每行x).因此x[n]如预期返回x的值. 我的问题是我需要通过i对这些x[n]进行排序(并且必须对y[n]进行同样的处理.

# Example data
x = np.array([14, 15,  9,  6, 19, 18,  4, 11, 10,  0])
i = np.argsort(x)
n = np.array([2, 5, 7, 8])

#x[n] -> array([ 9, 18, 11, 10])

所需输出:index_sort(x, n, i) = array([ 9, 10, 11, 18])

Some simple (failed) attempts: x[n][i] -> Indexing error, as x is now too small.
x[i[n]] -> array([ 6, 11, 15, 18]), Is sorted, but contains the wrong data
x[i][n] -> Same

For more context: I'm creating a specific type of decision tree model. For each layer of the tree I need the above operation a different n. Sorting becomes prohibitively expensive and even checking for set membership via np.isin might be too slow as well already. My intuition (though perhaps wrong) says it should be possible to achieve this via indexing only, without ever having to sort or check for set membership.
For all these layers x and i remain the same, but a different n is used each time.

推荐答案

In [263]: x = np.array([14, 15,  9,  6, 19, 18,  4, 11, 10,  0])
     ...: i = np.argsort(x)
     ...: n = np.array([2, 5, 7, 8])

in执行不同且不相关的索引操作. 两者都进行副本(而不是查看),其中不保留有关原始x的任何信息:

In [264]: x[i]
Out[264]: array([ 0,  4,  6,  9, 10, 11, 14, 15, 18, 19])

In [265]: x[n]
Out[265]: array([ 9, 18, 11, 10])

让我们try 使用布尔屏蔽:

In [266]: m = np.zeros_like(x, dtype=bool)    
In [267]: m[n] = True; m
Out[267]: 
array([False, False,  True, False, False,  True, False,  True,  True,
       False])

它从x中 Select 与n相同的元素(尽管它不会处理相同的重复项):

In [268]: x[m]
Out[268]: array([ 9, 18, 11, 10])

现在try 将排序应用于m:

In [269]: mi = m[i]; m
Out[269]: 
array([False, False,  True, False, False,  True, False,  True,  True,
       False])

它确实从排序后的x[i]个元素中 Select 所需的元素:

In [270]: x[i][mi]
Out[270]: array([ 9, 10, 11, 18])

我们还可以将布尔屏蔽转换回索引:

In [272]: ni = np.nonzero(mi)[0]; ni
Out[272]: array([3, 4, 5, 8], dtype=int64)
In [273]: x[i][ni]
Out[273]: array([ 9, 10, 11, 18])

Python相关问答推荐

使用decorator 重复超载

脚注在Python中使用regex导致错误匹配

如何匹配3D圆柱体的轴和半径?

有没有方法可以修复删除了换码字符的无效的SON记录?

从管道将Python应用程序部署到Azure Web应用程序,不包括需求包

Python -根据另一个数据框中的列编辑和替换数据框中的列值

使用scipy. optimate.least_squares()用可变数量的参数匹配两条曲线

Python会扔掉未使用的表情吗?

2维数组9x9,不使用numpy.数组(MutableSequence的子类)

如何将ctyles.POINTER(ctyles.c_float)转换为int?

将特定列信息移动到当前行下的新行

修复mypy错误-赋值中的类型不兼容(表达式具有类型xxx,变量具有类型yyy)

如何请求使用Python将文件下载到带有登录名的门户网站?

为什么抓取的HTML与浏览器判断的元素不同?

如何在表中添加重复的列?

删除marplotlib条形图上的底边

如何使用两个关键函数来排序一个多索引框架?

Flask Jinja2如果语句总是计算为false&

在输入行运行时停止代码

OpenCV轮廓.很难找到给定图像的所需轮廓