79518428

Date: 2025-03-18 19:02:11
Score: 0.5
Natty:
Report link

You’re trying to sort your DataFrame, but it’s a bit tricky to get the desired order, right? No worries, there’s a clean way to do this without loops. The key is to create a custom sorting logic for the Type column and then use it together with Time to keep the movements in the right sequence.

# import...
data = { # input here
    "ID": [1, 1, 1, 1, 1, 1, 1, 1],
    "Type": ["Enter", "Out", "In", "Out", "In", "Out", "In", "Exit"],
    "Department": ["A", "A", "A", "A", "A", "A", "B", "B"],
    "Time": ["11:00", "11:00", "11:00", "11:00", "11:00", "12:30", "12:30", "15:00"],
    "Code": [519, 519, 620, 620, 588, 588, 322, 322]
}
df = pd.DataFrame(data)
# sorting by 'Type'
sort_order = {"Enter": 0, "Out": 1, "In": 2, "Exit": 3} 
df['SortKey'] = df['Type'].map(sort_order)
# sorting by others...
df = df.sort_values(by=["ID", "Time", "SortKey", "Department"]).reset_index(drop=True)
Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Low reputation (1):
Posted by: Remigiusz Petrykowski