Julio S.
Julio S.

Reputation: 970

Pandas - how to sort rows of a column, using a dictionary with indexes

I have to sort the values/rows of a column of a Dataframe according to a dictionary, which contains each value of the dataframe and its row index, but sorted differently.

howToSortDict = {'Brazil': 2, 'Russia': 0, 'China': 1} # row value and its index

myDict = {
    "countries": ["Brazil", "Russia", "China"],
    "amount": [1000, 2000, 3000]
}

df = pd.DataFrame(myDict)

How they are sorted:

     countries  amount
0    Brazil     1000
1    Russia     2000
2    China      3000

How I need them to be sorted (as a dataframe):

    countries   amount
0   Russia      2000
1   China       3000
2   Brazil      1000

Any ideas of how to achieve this without looping over each row?

Upvotes: 3

Views: 2089

Answers (2)

BENY
BENY

Reputation: 323266

Use argsort

df=df.iloc[df.countries.map(howToSortDict).argsort()]
  countries  amount
1    Russia    2000
2     China    3000
0    Brazil    1000

Upvotes: 6

fmarm
fmarm

Reputation: 4284

In two steps:

First use map to create a new column with the values associated with the countries

df['country_value'] = df.countries.map(howToSortDict)

Then sort and drop the new column

df.sort_values('country_value').drop('country_value',axis=1)

#    countries   amount
#1   Russia      2000
#2   China       3000
#0   Brazil      1000

Upvotes: 3

Related Questions