注意尺寸。
让
x # initial numpy array
I = np.argsort(x) or I = x.argsort()
y = np.sort(x) or y = x.sort()
z # reverse sorted array
全反
z = x[I[::-1]]
z = -np.sort(-x)
z = np.flip(y)
-
flip 更改为 1.15,以前的版本 1.14 必需 axis。解决方案:pip install --upgrade numpy。
第一维反转
z = y[::-1]
z = np.flipud(y)
z = np.flip(y, axis=0)
第二维度反转
z = y[::-1, :]
z = np.fliplr(y)
z = np.flip(y, axis=1)
测试
在 100×10×10 阵列上测试 1000 次。
Method | Time (ms)
-------------+----------
y[::-1] | 0.126659 # only in first dimension
-np.sort(-x) | 0.133152
np.flip(y) | 0.121711
x[I[::-1]] | 4.611778
x.sort() | 0.024961
x.argsort() | 0.041830
np.flip(x) | 0.002026
这主要是由于重新索引而不是argsort。
# Timing code
import time
import numpy as np
def timeit(fun, xs):
t = time.time()
for i in range(len(xs)): # inline and map gave much worse results for x[-I], 5*t
fun(xs[i])
t = time.time() - t
print(np.round(t,6))
I, N = 1000, (100, 10, 10)
xs = np.random.rand(I,*N)
timeit(lambda x: np.sort(x)[::-1], xs)
timeit(lambda x: -np.sort(-x), xs)
timeit(lambda x: np.flip(x.sort()), xs)
timeit(lambda x: x[x.argsort()[::-1]], xs)
timeit(lambda x: x.sort(), xs)
timeit(lambda x: x.argsort(), xs)
timeit(lambda x: np.flip(x), xs)