在pandas中使用group by时,“first”和“last”函数到列失败

时间:2018-01-26 14:43:07

标签: python pandas numpy

我尝试实施了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))

感谢您的帮助!

1 个答案:

答案 0 :(得分: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