Python Forum
How to sort rows based on specific order - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to sort rows based on specific order (/thread-28693.html)



How to sort rows based on specific order - Mekala - Jul-30-2020

Hi,
I have below dataframe:
I want to arrange (based on column "Name") in the order [A, B,C,D] and by time

Ex:

A
B
C
D
A
B
C
D
A
B
C
D
Name    Time                 sequence   Rank
A       2020/07/20 20:13:20  W1         5 
C       2020/07/20 20:15:20  W1         5
D       2020/07/20 20:19:08  W1         1
B       2020/07/20 20:13:34  W1         5
A       2020/07/20 21:10:40  W2         11 
D       2020/07/20 21:15:20  W2         56
C       2020/07/20 21:19:35  W2         3
B       2020/07/20 21:15:52  W2         4
C       2020/07/20 22:10:40  W3         11 
B       2020/07/20 22:15:20  W3         56
A       2020/07/20 23:19:35  W3         3
D       2020/07/20 23:15:52  W3         4
Desiredoutput
A       2020/07/20 20:13:20  W1         5
B       2020/07/20 20:13:34  W1         5
C       2020/07/20 20:15:20  W1         5
D       2020/07/20 20:19:08  W1         1
A       2020/07/20 21:10:40  W2         11
B       2020/07/20 21:15:52  W2         4
C       2020/07/20 21:19:35  W2         3
D       2020/07/20 21:15:20  W2         56
A       2020/07/20 23:19:35  W3         3
B       2020/07/20 22:15:20  W3         56
C       2020/07/20 22:10:40  W3         11 
D       2020/07/20 23:15:52  W3         4
I searched but I could not find any similar hint(I can find sorting list only)


RE: How to sort rows based on specific order - bowlofred - Jul-30-2020

In your example they're sorted first by sequence number, then by Name. Is that always the case? If so, make your sort key a tuple with the sequence number first, then the name and you'll get that output.


RE: How to sort rows based on specific order - Mekala - Jul-31-2020

SOrt by "Name" column. then by time


RE: How to sort rows based on specific order - bowlofred - Jul-31-2020

I'm not sure how that would work. In the desired output show, neither the name nor the time are in sorted order. So sorting directly by time won't generate it.