program story

numpy 배열을 내림차순으로 효율적으로 정렬 하시겠습니까?

inputbox 2020. 9. 7. 08:07
반응형

numpy 배열을 내림차순으로 효율적으로 정렬 하시겠습니까?


이 특정 질문이 이전에 묻지 않은 것에 놀랐지 만 실제로 .NET 문서에서 찾지 못했습니다 np.sort.

정수를 보유하는 임의의 numpy 배열이 있다고 가정하십시오.

> temp = np.random.randint(1,10, 10)    
> temp
array([2, 4, 7, 4, 2, 2, 7, 6, 4, 4])

정렬하면 기본적으로 오름차순이 표시됩니다.

> np.sort(temp)
array([2, 2, 2, 4, 4, 4, 4, 6, 7, 7])

하지만 솔루션을 내림차순 으로 정렬하고 싶습니다 .

이제 저는 항상 할 수 있다는 것을 압니다.

reverse_order = np.sort(temp)[::-1]

하지만이 마지막 문장이 효율적 입니까? 오름차순으로 복사본을 만든 다음이 복사본을 뒤집어 결과를 역순으로 얻지 않습니까? 이것이 사실이라면 효율적인 대안이 있습니까? np.sort정렬 작업에서 비교 부호를 변경하여 역순으로 항목을 가져 오는 매개 변수를 받아들이지 않는 것 같습니다 .


temp[::-1].sort()배열을 제자리에 정렬하고 np.sort(temp)[::-1]새 배열을 만듭니다.

In [25]: temp = np.random.randint(1,10, 10)

In [26]: temp
Out[26]: array([5, 2, 7, 4, 4, 2, 8, 6, 4, 4])

In [27]: id(temp)
Out[27]: 139962713524944

In [28]: temp[::-1].sort()

In [29]: temp
Out[29]: array([8, 7, 6, 5, 4, 4, 4, 4, 2, 2])

In [30]: id(temp)
Out[30]: 139962713524944

>>> a=np.array([5, 2, 7, 4, 4, 2, 8, 6, 4, 4])

>>> np.sort(a)
array([2, 2, 4, 4, 4, 4, 5, 6, 7, 8])

>>> -np.sort(-a)
array([8, 7, 6, 5, 4, 4, 4, 4, 2, 2])

짧은 배열 np.argsort()의 경우 정렬 된 음수 배열의 인덱스를 찾아서 사용 하는 것이 좋습니다 . 이는 정렬 된 배열을 반대로하는 것보다 약간 빠릅니다.

In [37]: temp = np.random.randint(1,10, 10)

In [38]: %timeit np.sort(temp)[::-1]
100000 loops, best of 3: 4.65 µs per loop

In [39]: %timeit temp[np.argsort(-temp)]
100000 loops, best of 3: 3.91 µs per loop

불행히도 복잡한 배열이 있으면 np.sort(temp)[::-1]제대로 작동합니다. 여기에 언급 된 다른 두 가지 방법은 효과적이지 않습니다.


안녕하세요 저는 2 차원 numpy 배열을 역 정렬하는 솔루션을 찾고 있었는데 작동하는 것을 찾을 수 없었지만 누군가가 같은 보트에있는 경우를 대비하여 업로드하는 솔루션을 우연히 발견했다고 생각합니다.

x=np.sort(array)
y=np.fliplr(x)

np.sort는 원하는대로 오름차순으로 정렬하지만 fliplr 명령은 행을 왼쪽에서 오른쪽으로 뒤집습니다! 작동하는 것 같습니다!

도움이 되었기를 바랍니다.

I guess it's similar to the suggest about -np.sort(-a) above but I was put off going for that by comment that it doesn't always work. Perhaps my solution won't always work either however I have tested it with a few arrays and seems to be OK.


i suggest using this ...

np.arange(start_index, end_index, intervals)[::-1]

for example:

np.arange(10, 20, 0.5)
np.arange(10, 20, 0.5)[::-1]

Then your resault:

[ 19.5,  19. ,  18.5,  18. ,  17.5,  17. ,  16.5,  16. ,  15.5,
    15. ,  14.5,  14. ,  13.5,  13. ,  12.5,  12. ,  11.5,  11. ,
    10.5,  10. ]

Be careful with dimensions.

Let

x  # initial numpy array
I = np.argsort(x) or I = x.argsort() 
y = np.sort(x)    or y = x.sort()
z  # reverse sorted array

Full Reverse

z = x[-I]
z = -np.sort(-x)
z = np.flip(y)
  • flip changed in 1.15, previous versions 1.14 required axis. Solution: pip install --upgrade numpy.

First Dimension Reversed

z = y[::-1]
z = np.flipud(y)
z = np.flip(y, axis=0)

Second Dimension Reversed

z = y[::-1, :]
z = np.fliplr(y)
z = np.flip(y, axis=1)

Testing

Testing on a 100×10×10 array 1000 times.

Method       | Time (ms)
-------------+----------
y[::-1]      | 0.126659  # only in first dimension
-np.sort(-x) | 0.133152
np.flip(y)   | 0.121711
x[-I]        | 4.611778

x.sort()     | 0.024961
x.argsort()  | 0.041830
np.flip(x)   | 0.002026

This is mainly due to reindexing rather than 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()], xs)
timeit(lambda x: x.sort(), xs)
timeit(lambda x: x.argsort(), xs)
timeit(lambda x: np.flip(x), xs)

참고URL : https://stackoverflow.com/questions/26984414/efficiently-sorting-a-numpy-array-in-descending-order

반응형