Reputation: 1137
For example there's a DataFrame df
. And I want sort the rows based on the sequence s
in order to get df_target
. What's the correct way to achieve this purpose?
import pandas as pd
df = pd.DataFrame({'a': [3,4,2,5], 'b':['apple', 'orange', 'pear',
'grape']})
s = [4,5,2,3]
df_target = pd.DataFrame({'a': [4,5,2,3], 'b':['orange', 'grape',
'pear', 'apple']})
Upvotes: 0
Views: 49
Reputation: 394159
You could temporarily set the index to a
and then index using the list:
In[209]:
df.set_index('a').loc[s].reset_index()
Out[209]:
a b
0 4 orange
1 5 grape
2 2 pear
3 3 apple
Upvotes: 1