您可以使用panda在一行中的groupby对象中创建新列吗?

时间:2019-06-11 19:20:17

标签: python pandas pandas-groupby

我想知道是否能够在一行中执行以下操作,或者是否有必要在一行中执行以下操作(我来自R,所以我知道如何在一次调用中完成操作)。我想计算击球平均值,需要同时操纵击中次数和at bats列

import pandas as pd

batting = pd.DataFrame({'playerID': [1, 1, 1, 2, 2, 2],
                        'h': [80, 97, 95, 30, 35, 22],
                        'ab': [400, 410, 390, 150, 170, 145]})

batters = (batting.groupby('playerID')
                  .agg({'h' : 'sum', 'ab' : 'sum'})
                  .reset_index())

batters['ba'] = batters['h']/batters['ab']

1 个答案:

答案 0 :(得分:4)

eval is your friend

(batting.groupby('playerID')
        .agg({'h' : 'sum', 'ab' : 'sum'})
        .reset_index()
        .eval('ba = h / ab'))

   playerID    h    ab        ba
0         1  272  1200  0.226667
1         2   87   465  0.187097

您可以将其缩短为

batting.groupby('playerID', as_index=False).sum().eval('ba = h / ab')

   playerID    h    ab        ba
0         1  272  1200  0.226667
1         2   87   465  0.187097