Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Id Direction Load Unit
- 1 CN05059815 LoadFWD 0,0 NaN
- 2 CN05059815 LoadBWD 0,0 NaN
- 4 ....
- ....
- # sample dataframe
- df = pd.DataFrame({'col': ['A', 'B', 'C', 'D', 'E', 'F']})
- # required ordering
- lst = ['D', 'E', 'A', 'B']
- # convert to categorical
- df['col'] = df['col'].astype('category')
- # set order, adding values not in lst to the front
- order = list(set(df['col']) - set(lst)) + lst
- # attach ordering information to categorical series
- df['col'] = df['col'].cat.reorder_categories(order)
- # apply ordering
- df = df.sort_values('col')
- print(df)
- col
- 2 C
- 5 F
- 3 D
- 4 E
- 0 A
- 1 B
- df = pd.DataFrame({
- 'col': ['a', 'b', 'c', 'd', 'e']
- })
- list_ = ['d', 'b', 'a']
- print(df)
- col
- 0 a
- 1 b
- 2 c
- 3 d
- 4 e
- df.reindex(df.assign(dummy=df['col'])['dummy'].apply(lambda x: list_.index(x) if x in list_ else -1).sort_values().index)
- col
- 2 c
- 4 e
- 3 d
- 1 b
- 0 a
Add Comment
Please, Sign In to add comment