0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python::Numpyのarrayをインデックスソートする方法

Last updated at Posted at 2019-07-06

Pythonで、ソート時に、リストをソートするのではなく、ソートされたインデックスを返す場合。numpyのargsortを使った方法をご紹介します。

#CODE

argsort.py
#!/usr/bin/python3
import numpy

a=numpy.random.rand(10)
x=numpy.argsort(a)
print(a)
print(x)

b=a[x]
print(b)

z=x[-1::-1] # flip
print(z)

b=a[z]
print(b)

#stringの場合も同様に

a=numpy.array(['e','c','d','d','b','a'])
print(a)
x=numpy.argsort(a)
print(x)

b=a[x]
print (b)

#実行結果

[0.67958541 0.6855469  0.63389202 0.17932474 0.97544388 0.43904699
 0.35668947 0.17622098 0.53345127 0.15778868]
[9 7 3 6 5 8 2 0 1 4]
[0.15778868 0.17622098 0.17932474 0.35668947 0.43904699 0.53345127
 0.63389202 0.67958541 0.6855469  0.97544388]
[4 1 0 2 8 5 6 3 7 9]
[0.97544388 0.6855469  0.67958541 0.63389202 0.53345127 0.43904699
 0.35668947 0.17932474 0.17622098 0.15778868]
['e' 'c' 'd' 'd' 'b' 'a']
[5 4 1 2 3 0]
['a' 'b' 'c' 'd' 'd' 'e']
0
2
9

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?