James Wong
James Wong

Reputation: 1137

How to get rows with values of a column matching the same sequence of another sequence

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

Answers (1)

EdChum
EdChum

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

Related Questions