【问题标题】:“first” and “last” functions to columns while using group by in pandas fails在 pandas 中使用 group by 时对列的“first”和“last”函数失败
【发布时间】:2018-07-05 22:15:16
【问题描述】:

我尝试实施here 提供的解决方案,但我收到“无效语法” 我正在尝试获取最大值 + 第一/最后一个值。

我的代码如下所示:

groups = df[df['isTrade'] == 1].groupby('dateTime_s')                         
print(groups.agg({
      'Volume': np.sum,
      'tradePrice':[np.max,lambda x: x.iloc[0]], 
      }).head(160))

感谢您的帮助!

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    看来你需要GroupBy.first / GroupBy.last:

    df = pd.DataFrame({'tradePrice':[7,8,9,4,2,3],
                       'Volume':[1,3,5,7,1,0],
                       'isTrade':[2,1,1,1,2,4],
                       'dateTime_s':list('aaabbb')})
    
    print (df)
       Volume dateTime_s  isTrade  tradePrice
    0       1          a        2           7
    1       3          a        1           8
    2       5          a        1           9
    3       7          b        1           4
    4       1          b        2           2
    5       0          b        4           3
    
    groups = df[df['isTrade'] == 1].groupby('dateTime_s')  
    print(groups.agg({
          'Volume': 'sum',
          'tradePrice':['max','first'], 
          }).head(160))
    
               tradePrice       Volume
                      max first    sum
    dateTime_s                        
    a                   9     8      8
    b                   4     4      7
    

    【讨论】:

      猜你喜欢
      • 2013-02-06
      • 2012-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-14
      • 2014-08-21
      • 1970-01-01
      相关资源
      最近更新 更多