0

I need help with changing the order of elements in a column of my table. The elements are strings and I have a specific order that I would like them to be sorted.

For example if I would have a table of which one column would be days of the week I would want them to be ordered in a right way.

A header weekdays
smth friday
smth monday
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Sofia
  • 1

1 Answers1

1

Use pd.Categorical with ordered=True:

# sample data
df = pd.DataFrame({'a':['b','c', 'd'], 'day':['Mon', 'Fri', 'Tues']})

# all the week days in order you choose
weekdays = ['Mon','Tues', 'Fri']

# convert to categorical
df['day'] = pd.Categorical(df['day'], categories=weekdays, ordered=True)

# sort as usual
df.sort_values('day')

output:

   a   day
0  b   Mon
2  d  Tues
1  c   Fri
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74