我想对形状为[n,4]的numpy数组进行排序,沿第一维(大小:n)使用作用于第二维向量(大小:4)的自定义谓词。下面是我想要做的C++版本,实际上非常简单。我已经看到了如何使用python lists来完成这个任务,但我找不到使用numpy数组的语法。这可能吗?关于np.sort, np.argsort, np.lexsort的文档没有提到自定义谓词。
// c++ version
vector< float[4] > v = init_v();
float[4] p = init_p();
std::sort(v.begin(), v.end(), [&p](const auto& lhs, const auto& rhs) {
return myfn(p, lhs) > myfn(p, rhs); });
编辑: 以下是我想用于排序的Python代码。即对于我的数组的每一行(n:4),我将计算到一个固定点的欧几里得3D距离的平方(即仅考虑前3列)。
# these both operate on numpy vectors of shape [4] (i.e. a single row of my data matrix)
def dist_sq(a,b):
d = a[:3]-b[:3]
return np.dot(d*d)
def sort_pred(lhs, rhs, p):
return dist_sq(lhs, p) > dist_sq(rhs, p)
numpy.lexsort
代替numpy.argsort
。直接传递数组或者像这个问题/答案中那样应用谓词转换即可。 - MB-F