2

i have a dataframe with a row containing first names of people. Now i want to sort the dataframe on name but not on alphabetical order but on a given order. So for example I want to order my dataframe on row of names in the order:

L = ['marc','paul','beck','julia','rest']

If I have a dataframe containing a row with names I want the marc's at the top and then paul's, beck's etc.

How can i do this time efficient in python?

2
  • Can you share a sample of the dataframe? Commented Feb 26, 2019 at 11:04
  • This is just an example but the row containing the names looks like ['paul','paul','julia','marc','paul','beck','beck','julia'] Commented Feb 26, 2019 at 11:07

2 Answers 2

2

If need reorder data by column convert all values to ordered categoricals, so possible sort_values:

df = pd.DataFrame({'A':['paul','paul','julia','marc','paul','beck','beck','julia']})

L = ['marc','paul','beck','julia','rest']

df['A'] = pd.CategoricalIndex(df['A'], ordered=True, categories=L)

df = df.sort_values('A')
print (df)
       A
3   marc
0   paul
1   paul
4   paul
5   beck
6   beck
2  julia
7  julia
Sign up to request clarification or add additional context in comments.

Comments

1
L = ['marc','paul','beck','julia','rest']
df=pd.DataFrame()
df['L']=L

This gives you:

    L
0   marc
1   paul
2   beck
3   julia
4   rest

marc paul beck, in the right order.

1 Comment

then I just assign new values to the row, but it is a dataframe that I want to order on the given names

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.