Python(Numpy)数组排序

8 投票
4 回答
17724 浏览
提问于 2025-04-16 12:06

我有一个叫做 v 的数组,数据类型是 float64:

array([[  9.33350000e+05,   8.75886500e+06,   3.45765000e+02],
       [  4.33350000e+05,   8.75886500e+06,   6.19200000e+00],
       [  1.33360000e+05,   8.75886500e+06,   6.76650000e+02]])

... 这个数组是我通过 np.loadtxt 命令从一个文件中获取的。我想根据第一列的数值对它进行排序,但又不想打乱每一行中数字的结构。使用 v.sort(axis=0) 会让我得到:

array([[  1.33360000e+05,   8.75886500e+06,   6.19200000e+00],
       [  4.33350000e+05,   8.75886500e+06,   3.45765000e+02],
       [  9.33350000e+05,   8.75886500e+06,   6.76650000e+02]])

... 也就是说,它把第三列中最小的数字放到了第一行,等等。我其实想要的是这样的结果...

array([[  1.33360000e+05,   8.75886500e+06,   6.76650000e+02],
       [  4.33350000e+05,   8.75886500e+06,   6.19200000e+00],
       [  9.33350000e+05,   8.75886500e+06,   3.45765000e+02]])

... 这样每一行的元素之间的相对位置没有改变。

4 个回答

0

如果你在使用 v[:,0] 的时候发现有一些值是相同的,而你想要在第1列、第2列等进行二次排序,那么你可以使用 numpy.lexsort() 或者 numpy.sort(v, order=('col1', 'col2', etc..)。不过,如果你选择使用 order= 的方法,v 需要是一个结构化数组。

5

另外

可以试试

import numpy as np

order = v[:, 0].argsort()
sorted = np.take(v, order, 0)

'order' 是第一行的顺序。 然后 'np.take' 会根据这个顺序来取相应的列。

你可以查看 'np.take' 的帮助文档,内容如下:

help(np.take)

take(a, indices, axis=None, out=None, mode='raise') 从数组中沿着某个轴取出元素。

This function does the same thing as "fancy" indexing (indexing arrays
using arrays); however, it can be easier to use if you need elements
along a given axis.

Parameters
----------
a : array_like
    The source array.
indices : array_like
    The indices of the values to extract.
axis : int, optional
    The axis over which to select values. By default, the flattened
    input array is used.
out : ndarray, optional
    If provided, the result will be placed in this array. It should
    be of the appropriate shape and dtype.
mode : {'raise', 'wrap', 'clip'}, optional
    Specifies how out-of-bounds indices will behave.

    * 'raise' -- raise an error (default)
    * 'wrap' -- wrap around
    * 'clip' -- clip to the range

    'clip' mode means that all indices that are too large are

被替换为沿着该轴最后一个元素的索引。注意,这样做会禁用负数索引。

Returns
-------
subarray : ndarray
    The returned array has the same type as `a`.

See Also
--------
ndarray.take : equivalent method

Examples
--------
>>> a = [4, 3, 5, 7, 6, 8]
>>> indices = [0, 1, 4]
>>> np.take(a, indices)
array([4, 3, 6])

In this example if `a` is an ndarray, "fancy" indexing can be used.

>>> a = np.array(a)
>>> a[indices]
array([4, 3, 6])
13

试试这个

v[v[:,0].argsort()]

(这里的 v 是一个数组)。v[:,0] 表示第一列,而 .argsort() 会返回一个可以让第一列排序的索引列表。接着,你可以用这个索引列表对整个数组进行排序,使用的是高级索引。需要注意的是,这样得到的是一个排序后的数组副本。

我知道的唯一可以在原地排序数组的方法是使用记录类型(record dtype):

v.dtype = [("x", float), ("y", float), ("z", float)]
v.shape = v.size
v.sort(order="x")

撰写回答