在数据框中按条件对值进行排序

时间:2019-11-18 20:54:27

标签: 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)

以上方法均未提供所需的输出。

1 个答案:

答案 0 :(得分:2)

要做:

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上的文档:

  

升序:布尔值或布尔值列表,默认为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.