Guest User

Untitled

a guest
May 25th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.89 KB | None | 0 0
  1. Id Direction Load Unit
  2. 1 CN05059815 LoadFWD 0,0 NaN
  3. 2 CN05059815 LoadBWD 0,0 NaN
  4. 4 ....
  5. ....
  6.  
  7. # sample dataframe
  8. df = pd.DataFrame({'col': ['A', 'B', 'C', 'D', 'E', 'F']})
  9.  
  10. # required ordering
  11. lst = ['D', 'E', 'A', 'B']
  12.  
  13. # convert to categorical
  14. df['col'] = df['col'].astype('category')
  15.  
  16. # set order, adding values not in lst to the front
  17. order = list(set(df['col']) - set(lst)) + lst
  18.  
  19. # attach ordering information to categorical series
  20. df['col'] = df['col'].cat.reorder_categories(order)
  21.  
  22. # apply ordering
  23. df = df.sort_values('col')
  24.  
  25. print(df)
  26.  
  27. col
  28. 2 C
  29. 5 F
  30. 3 D
  31. 4 E
  32. 0 A
  33. 1 B
  34.  
  35. df = pd.DataFrame({
  36. 'col': ['a', 'b', 'c', 'd', 'e']
  37. })
  38. list_ = ['d', 'b', 'a']
  39. print(df)
  40.  
  41. col
  42. 0 a
  43. 1 b
  44. 2 c
  45. 3 d
  46. 4 e
  47.  
  48. df.reindex(df.assign(dummy=df['col'])['dummy'].apply(lambda x: list_.index(x) if x in list_ else -1).sort_values().index)
  49.  
  50. col
  51. 2 c
  52. 4 e
  53. 3 d
  54. 1 b
  55. 0 a
Add Comment
Please, Sign In to add comment