如何根据 Pandas 中另一个数据框中的列对数据框进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45576800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:12:40  来源:igfitidea点击:

How to sort dataframe based on a column in another dataframe in Pandas?

pythonpandas

提问by Jun Jang

enter image description here

在此处输入图片说明

Say I have two dataframes, df1 and df2 in the picture above. I want to sort the df1 based on the Col2 of df2.

假设我在上图中有两个数据帧,df1 和 df2。我想根据 df2 的 Col2 对 df1 进行排序。

So the end result of the df1 should look like the third dataframe in the picture, where the Col2 is in the same values, order in df2.

所以 df1 的最终结果应该看起来像图片中的第三个数据帧,其中 Col2 的值相同,按 df2 排序。

回答by Spandan Brahmbhatt

You can use combination of set_indexand reindexfor this.

为此,您可以使用set_index和 的组合reindex

Try this code :

试试这个代码:

df1 = pd.DataFrame({'Col1': ['a','b','c','d','e'], 'Col2': 
['chocolate','chicken','pizza','icecream','cake'] })
Out :
  Col1       Col2
0    a  chocolate
1    b    chicken
2    c      pizza
3    d   icecream
4    e       cake
df2 = pd.DataFrame({'Col1': ['f','g','h','i','j'], 'Col2': ['chicken','cake','icecream','chocolate','pizza'] })
Out :
  Col1       Col2
0    f    chicken
1    g       cake
2    h   icecream
3    i  chocolate
4    j      pizza
df1 = df1.set_index('Col2')
df1 = df1.reindex(index=df2['Col2'])
df1 = df1.reset_index()
Out :
        Col2 Col1
0    chicken    b
1       cake    e
2   icecream    d
3  chocolate    a
4      pizza    c