如果一列需要特定映射,如何对数据框中的多列进行排序?

问题描述 投票:0回答:1

我有一个数据框,我想根据 3 列对其进行排序,其中一列特别具有我想要使用的特定映射。例如,对于这个数据框:

enter image description here

我想按列

Code
Item
Type
对它进行排序,但特别是我想按特定的映射对
Type
进行排序,使其成为管理员、员工、用户、客户(因为我知道
Item
Code
列将始终具有至少 4 个相同值(例如给定示例中的 1 和 2),这不应该是问题)。因此,作为最终结果,我希望我的数据框看起来像这样:

enter image description here

在Python中,我知道如何按多列排序,我也知道如何按特定映射排序,但我不知道如何同时执行这两个操作,所以如果有人可以提供一些帮助,我会非常乐意感激不尽,谢谢!

python pandas dataframe sorting
1个回答
0
投票

代码

# your order of Type column
order = ['Admin', 'Staff', 'User', 'Customer']

# make mapper of your Type column order 
m = {key: n for n, key in enumerate(order)}

# sort by Code, Item and mapped Type column
out = df.sort_values(
    ['Code', 'Item', 'Type'], 
    key=lambda x: x.map(m) if x.name == 'Type' else x
)

  Code  Item      Type
3  AAA     1     Admin
2  AAA     1     Staff
1  AAA     1      User
0  AAA     1  Customer
6  AAA     2     Admin
4  AAA     2     Staff
5  AAA     2      User
7  AAA     2  Customer
8  BBB     1      User

示例代码

以代码或文本形式提供示例,而不是图像。

import pandas as pd
data = {'ID': [1, 1, 1, 2, 2, 3, 3, 4, 4, 4],
        'values': [34, 675, 45, 86, 4, 0, 45, 78, 24, 86],
        'source': ['XD', 'STAR', 'STAR', 'STAR', 'STAR', 'XD', 'STAR', 'XD', 'XD', 'STAR'],
        'type': ['x1', 'x2', 'x2', 'n6', 'n6', '9g', '9g', 'f8', 'f8', 'h6'],
        'function': ['abc', 'xyz', 'xyz', 'njf', 'njf', 'hu', 'hu', 'dj', 'dj', 'ed'],
        'values_new_column': [34, 45, 675, 4, 86, 45, 0, 24, 78, 86]}

df = pd.DataFrame(data)
© www.soinside.com 2019 - 2024. All rights reserved.