Pandas如何使用带索引的字典对列中的行进行排序

2024-09-30 01:18:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须根据字典对Dataframe列的值/行进行排序,字典包含Dataframe的每个值及其行索引,但排序不同

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)

它们是如何分类的:

     countries  amount
0    Brazil     1000
1    Russia     2000
2    China      3000

我需要如何对它们进行排序(作为数据帧):

    countries   amount
0   Russia      2000
1   China       3000
2   Brazil      1000

如何在不循环每一行的情况下实现这一点


Tags: anddataframeindex字典排序valueamountcountries
2条回答

分两步进行:

首先使用map创建一个新列,其中包含与国家/地区关联的值

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

然后sortdrop新列

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

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

使用argsort

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

相关问题 更多 >

    热门问题