python - 根据第一列对二维数组的行进行排序

标签 python arrays python-3.x sorting

我想在 Python 3 中根据第一列的元素对 2D 数组的行进行排序。例如,如果

    x = array([[ 5. ,  9. ,  2. ,  6. ],
               [ 7. , 12. ,  3.5,  8. ],
               [ 2. ,  6. ,  7. ,  9. ]])

然后我需要排序后的数组

    x = array([[ 2. ,  6. ,  7. ,  9. ],
               [ 5. ,  9. ,  2. ,  6. ],
               [ 7. , 12. ,  3.5,  8. ]])

我怎样才能做到这一点?提出并回答了类似的问题here ,但它对我不起作用。

最佳答案

以下内容应该有效:

import numpy as np
x = np.array([[ 5. ,  9. ,  2. ,  6. ],
               [ 7. , 12. ,  3.5,  8. ],
               [ 2. ,  6. ,  7. ,  9. ]])

x[x[:, 0].argsort()]
Out[2]:
array([[ 2. ,  6. ,  7. ,  9. ],
       [ 5. ,  9. ,  2. ,  6. ],
       [ 7. , 12. ,  3.5,  8. ]])

文档:numpy.argsort

关于python - 根据第一列对二维数组的行进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57434721/

相关文章:

ios - 基于NSDate将数组映射到字典

windows - 完全迷失在 "Installing"OpenCV/ctypes-opencv for Python 3

python - 当 pip install 'pyrebase' 时,出现错误 ' UnicodeDecodeError: ' cp94 9' codec can' t 在位置 500 : illegal multibyte sequence' 中解码字节 0xe2

python - Atlassian Bamboo 如何识别 python pytest 报告

python - matplotlib 图例无法与句柄正常工作

python - NE、SW 框内的 GeoDjango

hibernate ,PostgreSQL : Column "x" is of type oid but expression is of type byte

python - 使用正则表达式的问题

javascript - 用不重复的随机数填充数组

python - python 中包含有限字母表上的子字符串的字符串组合