Pandas how to apply multiple functions to dataframe

前端 未结 4 2184
粉色の甜心
粉色の甜心 2020-12-03 13:39

Is there a way to apply a list of functions to each column in a DataFrame like the DataFrameGroupBy.agg function does? I found an ugly way to do it like this:



        
4条回答
  •  自闭症患者
    2020-12-03 14:20

    For Pandas 0.20.0 or newer, use df.agg (thanks to ayhan for pointing this out):

    In [11]: df.agg(['mean', 'std'])
    Out[11]: 
               one       two
    mean  5.147471  4.964100
    std   2.971106  2.753578
    

    For older versions, you could use

    In [61]: df.groupby(lambda idx: 0).agg(['mean','std'])
    Out[61]: 
            one               two          
           mean       std    mean       std
    0  5.147471  2.971106  4.9641  2.753578
    

    Another way would be:

    In [68]: pd.DataFrame({col: [getattr(df[col], func)() for func in ('mean', 'std')] for col in df}, index=('mean', 'std'))
    Out[68]: 
               one       two
    mean  5.147471  4.964100
    std   2.971106  2.753578
    

提交回复
热议问题