Pandas: apply different functions to different columns

前端 未结 3 726
逝去的感伤
逝去的感伤 2020-12-16 19:49

When using df.mean() I get a result where the mean for each column is given. Now let\'s say I want the mean of the first column, and the sum of the second. Is t

3条回答
  •  死守一世寂寞
    2020-12-16 20:28

    You can try a closure:

    def multi_func(functions):
        def f(col):
            return functions[col.name](col)
        return f
    
    df = pd.DataFrame(np.random.random((10, 2)), columns=['A', 'B'])
    result = df.apply(multi_func({'A': np.mean, 'B': np.sum}))
    

提交回复
热议问题