Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add colmun with order number based on rules to DataFrame?

suggested below questions don’t sove my problem, because I want to add ordering based on rules. Suggested question don’t answer to that. And question is not a duplicate.
I have a DataFrame and I need to add a ‘new column’ with the order number of each value.
I was able to do that, but I wonder:
1- is there a more correct/elegant way to do this?
Also, is it possible:
2- to give equivalent numbers in the same order? For example in my case second and third rows have the same value, and is it possible to assign 2 for both of them?
3- to set rule for defining order for example, if difference between rows is less than 0,5 then they should be assigned the same row order. If more, then order number should increase.
Thank you in advance!

np.random.seed(42)
df2=pd.DataFrame(np.random.randint(1,10, 10), columns=['numbers'])
df2=df2.sort_values('numbers')
df2['ord']=1+np.arange(0, len(df2['numbers']))

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you want to use the same order number to identical "numbers", use groupby.ngroup:

df2['ord'] = df2.groupby('numbers').ngroup().add(1)

Output:

   numbers  ord
5        3    1
1        4    2
9        4    2
3        5    3
8        5    3
0        7    4
4        7    4
6        7    4
2        8    5
7        8    5

grouping with threshold

grouper = df2['numbers'].diff().gt(1).cumsum()
df2['ord_threshold'] = df2.groupby(grouper).ngroup().add(1)

Output:

   numbers  ord  ord_threshold
5        3    1              1
1        4    2              1
9        4    2              1
3        5    3              1
8        5    3              1
0        7    4              2
4        7    4              2
6        7    4              2
2        8    5              2
7        8    5              2
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading