【问题标题】:Python Pandas: efficiently aggregating different functions on different columns and combining the resulting columns togetherPython Pandas:有效地聚合不同列上的不同函数并将结果列组合在一起
【发布时间】:2019-12-27 08:01:50
【问题描述】:

到目前为止,我对标题中描述的任务的方法非常简单,但它似乎有些低效/unpythonic。我通常做的一个例子如下:


原来的 Pandas DataFramedf 有 6 列:'open', 'high', 'low', 'close', 'volume', 'new dt'

import pandas as pd

df_gb = df.groupby('new dt')

arr_high = df_gb['high'].max()
arr_low = df_gb['low'].min()
arr_open = df_gb['open'].first()
arr_close = df_gb['close'].last()
arr_volumne = df_gb['volume'].sum()

df2 = pd.concat([arr_open,
                 arr_high,
                 arr_low,
                 arr_close,
                 arr_volumne], axis = 'columns')

乍一看似乎已经很高效,但是当我有 20 个函数等待应用到 20 个不同的列时,它很快就会变得不合 Python/低效。

有什么方法可以让它更高效/pythonic?提前谢谢你

【问题讨论】:

    标签: python pandas performance aggregate pandas-groupby


    【解决方案1】:

    如果您有 20 个不同的函数,则无论如何您都必须将列与函数正确匹配。术语 pythonic 可能是主观的,所以这不是正确的答案,但可能有用。在我看来,你的方法是 Pythonic,它有点详细说明了正在发生的事情

    # as long as the columns are ordered with the proper functions
    # you may have to change the ordering here
    columns_to_agg = (column for column in df.columns if column != 'new dt')
    
    # if the functions are all methods of pandas.Series just use strings
    agg_methods = ['first', 'max', 'min', 'last', 'sum']
    
    # construct a dictionary and use it as aggregator
    agg_dict = dict((el[0], el[1]) for el in zip(columns_to_agg, agg_methods))
    df_gb = df.groupby('new dt', as_index=False).agg(agg_dict)
    

    如果您有想要应用的自定义功能,比如音量,您可以这样做

    
    def custom_f(series):
        return pd.notnull(series).sum()
    agg_methods = ['first', 'max', 'min', 'last', custom_f]
    

    其他一切都会好起来的。您甚至可以这样做以将 sum 和 custom_f 应用于您的音量列

    agg_methods = ['first', 'max', 'min', 'last', ['sum', custom_f]]
    

    【讨论】:

    • 感谢您的回复。我会尝试看看它是否有效。
    • np。如果有,请告诉我
    • 如果某些函数是用户定义的(如,未在 pandas 中定义为 'first'、'max' 之类的字符串)会发生什么?
    • 您可以将该功能作为字典的一部分。让我更新我的答案
    • 真的很感激
    【解决方案2】:
    In [3]: import pandas as pd                                                     
    In [4]: import numpy as np                                                      
    In [5]: df = pd.DataFrame([[1, 2, 3],[4, 5, 6],[7, 8, 9], 
    ...: [np.nan, np.nan, np.nan]],columns=['A', 'B', 'C']) 
    
    In [6]: df.agg({'A' : ['sum', 'min'], 'B' : ['min', 'max']})                    
    Out[6]: 
            A    B
    max   NaN  8.0
    min   1.0  2.0
    sum  12.0  NaN
    

    对于作为列的函数:

    In [11]: df.agg({'A' : ['sum'], 'B' : ['min', 'max']}).T                        
    Out[11]: 
       max  min   sum
    A  NaN  NaN  12.0
    B  8.0  2.0   NaN
    

    要使用自定义函数,您可以这样做:

    In [12]: df.agg({'A' : ['sum',lambda x:x.mean()], 'B' : ['min', 'max']}).T      
    Out[12]: 
       <lambda>  max  min   sum
    A       4.0  NaN  NaN  12.0
    B       NaN  8.0  2.0   NaN
    

    【讨论】:

    • 谢谢,很高兴知道自定义函数可以这样使用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-26
    • 2018-12-12
    • 2015-08-20
    • 2021-11-10
    • 2019-03-04
    • 1970-01-01
    相关资源
    最近更新 更多