我想根据 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/