python - 根据数据框中的条件对值进行排序

标签 python pandas

我想根据 col1 按降序对 col2 进行排序。我感觉答案很简单,但我找不到正确的方法。我将非常感谢一些帮助。

数据框看起来像:

Col1 Col2 Col3 
AB   5    Blue
AB   1    Red
AB   2    Green
AC   1    Red
AC   4    Blue
AD   9    Red
AD   5    Blue
AD   7    Green

所需的输出:

Col1 Col2 Col3 
 AB   5    Blue
 AB   2    Green
 AB   1    Red
 AC   4    Blue
 AC   1    Red
 AD   9    Red
 AD   7    Green
 AD   5    Blue

我尝试过的:

df = pd.read_csv('data.csv')
df.sort_values(['Col1','Col2'], ascending = False)
df.groupby(['Col1'])['Col2'].sort_values(ascending = False)

上述方法均未给出所需的输出。

最佳答案

做:

print(df.sort_values(['Col1', 'Col2'], ascending=[True, False]))

输出

  Col1  Col2   Col3
0   AB     5   Blue
2   AB     2  Green
1   AB     1    Red
4   AC     4   Blue
3   AC     1    Red
5   AD     9    Red
7   AD     7  Green
6   AD     5   Blue

来自 sort_values 的文档:

ascending : bool or list of bool, default True

Sort ascending vs. descending. Specify list for multiple sort orders. If this is a list of bools, must match the length of the by.

关于python - 根据数据框中的条件对值进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58922749/

相关文章:

python - 为什么文件处理程序不能在 python 中多次使用?

python pandas to_sql 与 sqlalchemy : how to speed up exporting to MS SQL?

python - 如果 Pandas 满足条件,则更新列

python - 检查字符串是否在 pandas 数据框中并修改行

python - 查找屏蔽的 CI/CD 变量的值

python - 如何确定客户端是否需要 JSON 响应

python - 如何获取 Pandas 数据帧每一行中特定值的频率

python - python 中的向量化 get() 方法

python - 我如何在Python中循环函数变量?

python - 从列表中获取元素,循环方式