[英]Sort 2D NumPy array by one of the columns
I though this would be super easy but I am struggling a little. 我虽然这很容易,但是我有点挣扎。 I have a data structure as follows 我的数据结构如下
array([[ 5. , 3.40166205],
[ 10. , 2.72778882],
[ 15. , 2.31881804],
[ 20. , 2.50643777],
[ 1. , 3.94076063],
[ 2. , 3.80598599],
[ 3. , 3.67121134],
[ 6. , 3.2668874 ],
[ 7. , 3.13211276],
[ 8. , 2.99733811],
[ 9. , 2.86256347],
[ 11. , 2.64599467],
[ 12. , 2.56420051],
[ 13. , 2.48240635],
[ 14. , 2.4006122 ],
[ 16. , 1.8280531 ],
[ 17. , 1.74625894],
[ 18. , 1.66446479],
[ 19. , 1.58267063],
[ 20. , 1.50087647]])
And I want to sort it ONLY on the first column ... so it is ordered as follows: 而且我只希望在第一列上对其进行排序...因此,其排序如下:
array([[1. , 3.9],
[2. , 3.8],
... ,
[20. , 1.5]])
np.sort
doesn't seem to work as it moves array to a flat structure. np.sort
似乎无法正常工作,因为它将数组移至平面结构。 I've also used itemgetter
我也用了itemgetter
from operator import itemgetter
sorted(data, key=itemgetter(1))
But this doesn't give me the output I'm looking for. 但这并不能为我提供所需的输出。
Help appreciated! 帮助赞赏!
This is a common numpy idiom. 这是一个常见的numpy成语。 You can use argsort
(on the first column) + numpy indexing here - 您可以在此处使用argsort
(在第一列上)+ numpy索引-
x[x[:, 0].argsort()]
array([[ 1. , 3.94076063],
[ 2. , 3.80598599],
[ 3. , 3.67121134],
[ 5. , 3.40166205],
[ 6. , 3.2668874 ],
[ 7. , 3.13211276],
[ 8. , 2.99733811],
[ 9. , 2.86256347],
[ 10. , 2.72778882],
[ 11. , 2.64599467],
[ 12. , 2.56420051],
[ 13. , 2.48240635],
[ 14. , 2.4006122 ],
[ 15. , 2.31881804],
[ 16. , 1.8280531 ],
[ 17. , 1.74625894],
[ 18. , 1.66446479],
[ 19. , 1.58267063],
[ 20. , 2.50643777],
[ 20. , 1.50087647]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.