0

I have a dataframe with two columns as sted below:

Col 1       Col2
  A         RED
  B         GREEN
  C         AMBER
  D          RED
  E          GREEN

I want the output dataframe as:

Col1        Col2
 A           RED
 D           RED
 C           AMBER
 B            GREEN
 E            GREEN

I want the column to be sorted in the order of priorty red,amber and green irrespective of column 1 value.

Thanks for any help in advance

0

2 Answers 2

3

Another solution :

  #create a mapping of the sort order
  sortbox = {'RED':1,'AMBER':2,'GREEN':3}

  #create new column with the sort order
  df['sort_column'] = df.Col2.map(sortbox)

  #sort with sort_column

 df.sort_values('sort_column').drop('sort_column',axis=1).reset_index(drop=True)


   Col 1    Col2
0   A       RED
1   D       RED
2   C       AMBER
3   B       GREEN
4   E       GREEN
Sign up to request clarification or add additional context in comments.

Comments

1

One way to do this is by adding another column which contains the second letter of each row in col2 and sort by it (that's the only sorting order I found suitable for your question):

d1 = {'col1': ['A', 'B', 'C', 'D', 'E'], 'col2': ['RED', 'GREEN', 'AMBER', 'RED', 'GREEN']}
df1 = pd.DataFrame(data=d1)
df1['col3'] = [i[1] for i in df1['col2']]
df1 = df1.sort_values(by='col3')

The result, after excluding 3rd column, is like the one you posted

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.