python - 使用 Pandas 自定义排序

标签 python sorting pandas

我有以下数据框,我想先按关键程度排序,然后按名称排序:

Name        Criticality
baz         High
foo         Critical
baz         Low
foo         Medium
bar         High
bar         Low
bar         Medium
...

我一直在尝试使用 this post 中提供的答案来做到这一点但我就是无法让它工作。

最终的结果应该是这样的

Name        Criticality
bar         High
bar         Medium
bar         Low
baz         High
baz         Low
foo         Critical
foo         Medium

最佳答案

一种方法是使用自定义字典创建一个“排名”列,然后我们使用排序,然后在排序后删除该列:

In [17]:
custom_dict = {'Critical':0, 'High':1, 'Medium':2, 'Low':3}  
df['rank'] = df['Criticality'].map(custom_dict)
df

Out[17]:

  Name Criticality  rank
0  baz        High     1
1  foo    Critical     0
2  baz         Low     3
3  foo      Medium     2
4  bar        High     1
5  bar         Low     3
6  bar      Medium     2

[7 rows x 3 columns]

In [19]:
# now sort by 'Name' and 'rank', it will first sort by 'Name' column first and then 'rank'
df.sort(columns=['Name', 'rank'],inplace=True)
df

Out[19]:

  Name Criticality  rank
4  bar        High     1
6  bar      Medium     2
5  bar         Low     3
0  baz        High     1
2  baz         Low     3
1  foo    Critical     0
3  foo      Medium     2

[7 rows x 3 columns]

In [21]:
# now drop the 'rank' column
df.drop(labels=['rank'],axis=1)

Out[21]:

  Name Criticality
4  bar        High
6  bar      Medium
5  bar         Low
0  baz        High
2  baz         Low
1  foo    Critical
3  foo      Medium

[7 rows x 2 columns]

关于python - 使用 Pandas 自定义排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23279238/

相关文章:

c++ - std::set 和 < 运算符重载的奇怪行为?

python - Pandas `agg` 列出, "AttributeError/ValueError: Function does not reduce"

jquery - Cherrypy:::无法加载index.html

python - 如何在 5 分钟内使 Django session 过期?

powershell - 根据文件名中间的版本号对文件进行排序

javascript - 对链接数组进行排序

python - 创建随机值并将其传递给具有硬边界的 Pandas 数据帧

python - 获取 Pandas 数据框中满足特定条件的行(字符串)的百分比

Python、线程和 gobject

python - 更新 anaconda 和 python 后 'import matplotlib.pyplot as plt' 不再工作