3

I have the following array : (3,2,3,4,7,2,4,7)* which I need to renumber to : (1,0,1,2,3,0,2,3)

ie : the lowest value should become 0, the second lowest should become 1, etc.

The similar posts I could find have only one instance of each number, and the related answers cannot apply here because the repeated numbers should have the same renumber value.

Thank you

  • the actual array has thousands of numbers.
Michael
  • 31
  • 2

1 Answers1

1

This may not be the most efficient solution, as I suspect there are one-liners, but I hope it is sensible and straightforward:

from collections import defaultdict

ary = [3,2,3,4,7,2,4,7]

#you don't need a defaultdict, but I like to use them just in case, instead of a dictionary, as a general practice
rank = defaultdict(int)

for x in ary: #first, we get all the values of the array and put them in the dict
    rank[x] = 0

count = 0

for x in sorted(rank): #now we go from lowest to highest in the array, adding 1 to the dict-value
    rank[x] = count
    count += 1

ary = [rank[x] for x in ary]

print(ary)
aschultz
  • 1,658
  • 3
  • 20
  • 30
  • Perfect! I do not understand the logic yet, but it works. Thanks for your prompt help. Btw, what is a one-liner ? (I am a python beginner). – Michael Aug 10 '19 at 16:18
  • First, glad I could help, and let me know what needs clarification! I tried to add it where I thought I would most need it, but different people need find diffrent things helpful. Second a one-liner means that something can be done in one line of code, which is good if it's concise, because it can help the reader save time in the future. But if the line runs on too long, it defeats the purpose--it is too hard to read. – aschultz Aug 10 '19 at 17:06
  • Ah ok, it’s clear now. Thanks a lot. – Michael Aug 11 '19 at 17:03