【问题标题】:Getting maximum values in a column获取列中的最大值
【发布时间】:2019-10-23 22:19:47
【问题描述】:

我的数据框如下所示:

Country Code Duration
A        1     0
A        1     1
A        1     2
A        1     3
A        2     0
A        2     1
A        1     0
A        1     1
A        1     2

我需要从“持续时间”列中获取最大值——不仅是最大值,而且是该列中每个数字序列的最大值列表。输出可能如下所示:

Country Code Duration
  A      1     3
  A      2     1
  A      1     2

我本可以按“代码”分组,但它的值经常重复,所以这可能不是一个选项。任何帮助或提示将不胜感激。

【问题讨论】:

  • 问题陈述有点不清楚,提供的输出令人困惑。您实际上是在显示所需的输出还是只是输出的形式?如果是前者,请解释如何获得该输出。如果是后者,请提供实际所需输出的示例。
  • @GZ0 这是所需的输出。持续时间列由从 0 到 n 的值序列组成,我只需要获取这些 n 值。例如,第一个序列的范围是 0 到 3,因此输出中的第一行是 3 表示 Duration;第 2 个序列的范围是 0 到 1,输出中的第 2 行是 1;最后一个序列的范围是 0 到 2,因此输出中的最后一行是 2 表示 Duration。

标签: python pandas


【解决方案1】:

在通过diffcumsum 创建另一个组密钥后使用idxmax

df.loc[df.groupby([df.Country,df.Code.diff().ne(0).cumsum()]).Duration.idxmax()]
  Country  Code  Duration
3       A     1         3
5       A     2         1
8       A     1         2

【讨论】:

    【解决方案2】:

    首先我们创建一个掩码来标记序列。然后我们 groupby 来创建想要的输出:

    m = (~df['Code'].eq(df['Code'].shift())).cumsum()
    
    df.groupby(m).agg({'Country':'first',
                       'Code':'first',
                       'Duration':'max'}).reset_index(drop=True)
    

      Country  Code  Duration
    0       A     1         3
    1       A     2         1
    2       A     1         2
    

    【讨论】:

    • 我认为as_index=False 可能会在groupby 调用中使用,以避免最后的reset_index 调用。
    【解决方案3】:

    您可能想查看此链接,这可能是您正在寻找的答案: pandas groupby where you get the max of one column and the min of another column 。它是:

    result = df.groupby(['Code', 'Country']).agg({'Duration':'max'})[['Duration']].reset_index()
    

    【讨论】:

      【解决方案4】:

      这个问题有点不清楚。但是,假设顺序很重要,我们可以找到解决方案。

      import pandas as pd
      d = pd.read_csv('data.csv')
      
      s = d.Code
      d['series'] = s.ne(s.shift()).cumsum()
      print(pd.DataFrame(d.groupby(['Country','Code','series'])['Duration'].max().reset_index()))
      

      返回:

       Country  Code  series  Duration
      0       A     1       1         3
      1       A     1       3         2
      2       A     2       2         1
      

      然后您可以删除该系列。

      【讨论】:

        猜你喜欢
        • 2014-12-21
        • 1970-01-01
        • 2010-11-23
        • 2020-09-22
        • 1970-01-01
        • 1970-01-01
        • 2018-10-14
        • 1970-01-01
        相关资源
        最近更新 更多