【发布时间】:2018-01-29 15:50:16
【问题描述】:
我想使用对第二维向量 (size:4) 进行操作的自定义谓词,沿第一维 (size:n) 对形状为 [n,4] 的 numpy 数组进行排序。我想做的 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代码。 IE。对于我的数组的每个“行”(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)
【问题讨论】:
标签: python arrays sorting numpy