I want to get the rank of Python List values in ascending / descending order. I found the ascending order as soon as I looked it up, but I left it as a memo because the descending order required some ingenuity.
It's a code right away.
from scipy.stats import rankdata
# Target data
array = [10,30,30,40,20]
# Get the rank for each index with rankdata
asc = rankdata(array)
# Display in ascending order
print(type(asc))
print(asc.astype(float))
# Descending calculation
desc = (len(asc) - asc + 1).astype(float)
# Display in descending order
print(type(desc))
print(desc)
It seems that the process of acquiring in descending order is not implemented in rankdata, so it was necessary to calculate the descending order. As a result of trying various things, I feel that this seems to be the easiest.
Below are the execution results.
<class 'numpy.ndarray'>
[1. 3. 5. 4. 2.]
<class 'numpy.ndarray'>
[5. 3. 1. 2. 4.]
If you change astype to astype (int)
<class 'numpy.ndarray'>
[1 3 5 4 2]
<class 'numpy.ndarray'>
[5 3 1 2 4]
It will be like this.
If the same value is entered in this state ...
# Target data
array = [10,30,30,40,20]
<class 'numpy.ndarray'>
[1 3 3 5 2]
<class 'numpy.ndarray'>
[5 2 2 1 4]
It will be like this. The result has changed. If it stays float
<class 'numpy.ndarray'>
[1. 3.5 3.5 5. 2. ]
<class 'numpy.ndarray'>
[5. 2.5 2.5 1. 4. ]
It will be like this.
When the data is not covered, it is a limited method.
The method pointed out by konandoirusa is overwhelmingly easier, so I added it.
import numpy as np
from scipy.stats import rankdata
# Target data
array = [10,30,30,40,20]
# ascending order
print(rankdata(np.array(array)))
# descending order
print(rankdata(-np.array(array)))
Execution result
[1. 3.5 3.5 5. 2. ]
[5. 2.5 2.5 1. 4. ]
Recommended Posts