假设我在上图中有两个数据帧df1和df2。我想根据df2的Col2对df1进行排序。
因此,df1的最终结果应该看起来像图片中的第三个数据帧,其中Col2的值相同,以df2的顺序排列。
您可以为此使用set_index和的组合reindex。
试试这个代码:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4439 次 |
| 最近记录: |