Python Pandas average based on condition into new column

前端 未结 3 1085
猫巷女王i
猫巷女王i 2021-02-09 16:49

I have a pandas dataframe containing the following data:

matchID    server    court    speed
1          1         A         100
1          2         D         20         


        
3条回答
  •  终归单人心
    2021-02-09 17:52

    You can get the mean by groupby and assign the values by getting the item() i.e

    vals = df[df['server'].isin([1,3])].groupby(['court'])['speed'].mean().to_frame()
    
    
    df['A13'],df['D13'] = vals.query("court=='A'")['speed'].item(), vals.query("court=='D'")['speed'].item()
    
        matchID  server court  speed    A13    D13
    0         1       1     A    100  110.0  205.0
    1         1       2     D    200  110.0  205.0
    2         1       3     D    300  110.0  205.0
    3         1       4     A    100  110.0  205.0
    4         1       1     A    120  110.0  205.0
    5         1       2     A    250  110.0  205.0
    6         1       3     D    110  110.0  205.0
    7         1       4     D    100  110.0  205.0
    8         2       1     A    100  110.0  205.0
    9         2       2     D    200  110.0  205.0
    10        2       3     D    300  110.0  205.0
    11        2       4     A    100  110.0  205.0
    12        2       1     A    120  110.0  205.0
    13        2       2     A    250  110.0  205.0
    14        2       3     D    110  110.0  205.0
    15        2       4     D    100  110.0  205.0
    

提交回复
热议问题