【问题标题】:Sorting values with condition in a dataframe在数据框中按条件对值进行排序
【发布时间】:2019-11-19 07:11:04
【问题描述】:

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

上述方法都没有提供所需的输出。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    做:

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

    升序:bool或bool列表,默认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.
    

    【讨论】:

      猜你喜欢
      • 2021-10-29
      • 2022-11-12
      • 2021-06-25
      • 1970-01-01
      • 2015-12-29
      • 2016-09-05
      • 2021-05-15
      • 2010-11-20
      相关资源
      最近更新 更多