如何根据 pandas 中另一个数据框中的列对数据框进行排序? [英] How to sort dataframe based on a column in another dataframe in Pandas?

查看:44
本文介绍了如何根据 pandas 中另一个数据框中的列对数据框进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我上图中有两个数据帧df1和df2. 我想根据df2的Col2对df1进行排序.

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的最终结果应该看起来像图片中的第三个数据帧,其中Col2的值相同,在df2中的顺序为

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.

推荐答案

您可以为此使用set_indexreindex的组合.

You can use combination of set_index and reindex for this.

尝试此代码:

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

这篇关于如何根据 pandas 中另一个数据框中的列对数据框进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆