简体   繁体   中英

How to replace the number values of a column by low to high in python?

i have this:

A 29
B 45
C 75
D 22
E 58
E 58
F 61
G 47
G 47

and i need to get this:

A 2 
B 3
C 7
D 1
E 5
E 5
F 6
G 4
G 4

i think about sort ascending and rank and after change the column values but this is not applied to the duplicates in the first column. Need the equal values in column 1 has the same rank value in the column 2. Anyone?

You can sort the values, enumerate that, then loop through the original data getting the indexes of the value of the original data. Below is an example of what I mean: (just implement it to your needs)

data = {
    "A": 29,
    "B": 45,
    "C": 75,
    "D": 22,
    "E": 58,
    "E": 58,
    "F": 61,
    "G": 47,
}

sorted_data = dict(map(reversed, enumerate(sorted(data.values()), 1)))

result = {k: sorted_data[v] for k, v in data.items()}

result

{'A': 2, 'B': 3, 'C': 7, 'D': 1, 'E': 5, 'F': 6, 'G': 4}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM