我有以下numpy矩阵,我想按升序排序基于第3列值。
[[ 3.05706500e+06 4.98000000e+01 -2.62500070e+01 -9.38135544e+01]
[ 3.05706600e+06 4.98000000e+01 -3.00000056e+01 -9.38135544e+01]
[ 3.05706700e+06 4.98000000e+01 -3.37500042e+01 -9.38135544e+01]
[ 3.05706800e+06 4.98000000e+01 -3.75000028e+01 -9.38135544e+01]]
这是我真正想要的矩阵。
[[ 3.05706800e+06 4.98000000e+01 -3.75000028e+01 -9.38135544e+01]
[ 3.05706700e+06 4.98000000e+01 -3.37500042e+01 -9.38135544e+01]
[ 3.05706600e+06 4.98000000e+01 -3.00000056e+01 -9.38135544e+01]
[ 3.05706500e+06 4.98000000e+01 -2.62500070e+01 -9.38135544e+01]]
如何使用numpy来做到这一点?任何帮助,将不胜感激。谢谢!
答案 0 :(得分:17)
给出你的阵列
>>> arr
array([[ 3.05706500e+06, 4.98000000e+01, -2.62500070e+01,
-9.38135544e+01],
[ 3.05706600e+06, 4.98000000e+01, -3.00000056e+01,
-9.38135544e+01],
[ 3.05706700e+06, 4.98000000e+01, -3.37500042e+01,
-9.38135544e+01],
[ 3.05706800e+06, 4.98000000e+01, -3.75000028e+01,
-9.38135544e+01]])
你可以简单地使用轴= 0的numpy.sort来根据需要对其进行排序
>>> numpy.sort(arr,axis=0)
array([[ 3.05706500e+06, 4.98000000e+01, -3.75000028e+01,
-9.38135544e+01],
[ 3.05706600e+06, 4.98000000e+01, -3.37500042e+01,
-9.38135544e+01],
[ 3.05706700e+06, 4.98000000e+01, -3.00000056e+01,
-9.38135544e+01],
[ 3.05706800e+06, 4.98000000e+01, -2.62500070e+01,
-9.38135544e+01]])
>>>
我相信我之前的回答是错误的,因为我误解了这个问题。这是正确的答案
>>> arr[arr[:,2].argsort()]
array([[ 3.05706800e+06, 4.98000000e+01, -3.75000028e+01,
-9.38135544e+01],
[ 3.05706700e+06, 4.98000000e+01, -3.37500042e+01,
-9.38135544e+01],
[ 3.05706600e+06, 4.98000000e+01, -3.00000056e+01,
-9.38135544e+01],
[ 3.05706500e+06, 4.98000000e+01, -2.62500070e+01,
-9.38135544e+01]])
>>>