Pandas: apply different functions to different columns

前端 未结 3 725
逝去的感伤
逝去的感伤 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:20

    Just faced this situation myself and came up with the following:

    In [1]: import pandas as pd
    
    In [2]: df = pd.DataFrame([['one', 'two'], ['three', 'four'], ['five', 'six']], 
       ...:                   columns=['A', 'B'])
    
    In [3]: df
    Out[3]: 
           A     B
    0    one   two
    1  three  four
    2   five   six
    
    In [4]: converters = {'A': lambda x: x[:1], 'B': lambda x: x.replace('o', '')}
    
    In [5]: new = pd.DataFrame.from_dict({col: series.apply(converters[col]) 
       ...:                               if col in converters else series
       ...:                               for col, series in df.iteritems()})
    
    In [6]: new
    Out[6]: 
       A    B
    0  o   tw
    1  t  fur
    2  f  six
    

提交回复
热议问题