4
3

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]List内の値の順位を昇順/降順で取得する

Last updated at Posted at 2020-02-25

記事の内容

PythonのListの値の順位を昇順/降順で取得したい。
昇順は調べるとすぐに見つかりましたが、降順は少し工夫が必要だったのでメモとして残します。

コード

早速、コードです。

sample.py
from scipy.stats import rankdata

# 対象のデータ
array = [10,30,30,40,20]

# rankdataでインデックス毎の順位を取得
asc = rankdata(array)

# 昇順の表示
print(type(asc))
print(asc.astype(float))

# 降順の計算
desc = (len(asc) - asc + 1).astype(float)

# 降順の表示
print(type(desc))
print(desc)

降順はrankdataに降順で取得する処理が実装されていない様なので計算する必要がありました。
色々試してみた結果、これが一番簡単に出来そうな気がします。

以下、実行結果です。

<class 'numpy.ndarray'>
[1. 3. 5. 4. 2.]
<class 'numpy.ndarray'>
[5. 3. 1. 2. 4.]

astypeをastype(int)に変更すると

<class 'numpy.ndarray'>
[1 3 5 4 2]
<class 'numpy.ndarray'>
[5 3 1 2 4]

こうなります。

この状態で同じ値が入っていると・・

# 対象のデータ
array = [10,30,30,40,20]
<class 'numpy.ndarray'>
[1 3 3 5 2]
<class 'numpy.ndarray'>
[5 2 2 1 4]

こうなります。結果が変わってしまいました・。
floatのままだと

<class 'numpy.ndarray'>
[1.  3.5 3.5 5.  2. ]
<class 'numpy.ndarray'>
[5.  2.5 2.5 1.  4. ]

こうなります。

データに被りがない時、限定のやり方ということで・・。

追記

konandoirusa さんよりご指摘頂いた方法の方が圧倒的に簡単なので追記

sample.py
import numpy as np
from scipy.stats import rankdata
# 対象のデータ
array = [10,30,30,40,20]

# 昇順
print(rankdata(np.array(array)))
# 降順
print(rankdata(-np.array(array)))

実行結果

[1.  3.5 3.5 5.  2. ]
[5.  2.5 2.5 1.  4. ]
4
3
1

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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?