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)