Python Numpy Sort rows [duplicate]

自古美人都是妖i 提交于 2021-01-20 11:48:12

问题


Very new to Python so please bear with me here. I am trying to sort an array that I have imported into python with numpy.sort:

 guy = numpy.sort(sasBody, axis=-0)

The first column is a column of strings, so I would like to alphabetically sort the array. The problem I am having is that it does sort the first column, however all the numbers associated with the prior rows are now not connected to its correct first column counterpart.

What am I doing wrong?


回答1:


You need to use np.lexsort though in case of strings that may not work. As a work around, you may use np.argsort

>>> a
array([['xyz', 0],
       ['abc', 5],
       ['ijk', 10]], dtype=object)
>>> i = np.argsort(a[:,0])
>>> a[i]
array([['abc', 5],
       ['ijk', 10],
       ['xyz', 0]], dtype=object)



回答2:


Sorry a little bit more digging found me the answer guy = sasBody[np.argsort(sasBody[:, 0])]



来源:https://stackoverflow.com/questions/30529095/python-numpy-sort-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!