熊猫套用功能慢速

时间:2019-12-18 02:21:06

标签: python pandas apply

我有一个数据帧(大约1-3 M条记录),我在上面运行apply()函数。这需要花费大量时间。我读过一些我不应该使用apply()的地方,但是我不确定如何完成它而不用完成它。

数据框是交易销售数据。我按“ APN”分组,然后重新创建一个新的pd.Series

def f(x):
    d = {}
    d['fips_2'] = x["fips"].values[0]
    d['apn_2'] = x["apn"].values[0]
    d['most_recent_sale'] = x["recording_date"].nlargest(1).iloc[-1]
    d['second_most_recent_sale'] = x["recording_date"].nlargest(2).iloc[-1]
    d['third_most_recent_sale'] = x["recording_date"].nlargest(3).iloc[-1]
    d['most_recent_price'] = x.loc[x["recording_date"] == d["most_recent_sale"], "price"].values[0]
    d['second_most_recent_price'] = x.loc[x["recording_date"] == d["second_most_recent_sale"], "price"].values[0]
    d['third_most_recent_price'] = x.loc[x["recording_date"] == d["third_most_recent_sale"], "price"].values[0]
    d['second_grantor'] = x.loc[x["recording_date"] == d["most_recent_sale"], "seller"].values[0]
    d['prior_grantor'] = x.loc[x["recording_date"] == d["second_most_recent_sale"], "seller"].values[0]
    d['type'] = x["type"].values[0]

    print(x["apn"].values[0])

    return pd.Series(d, index=['apn_2', 'most_recent_sale', 'second_most_recent_sale', 'most_recent_price', 'second_most_recent_price', 'second_grantor', 'type'])

df_grouped = year_past_df.groupby("apn").apply(f)

是否有更好的方法可以更快地完成相同任务?

1 个答案:

答案 0 :(得分:0)

一项改进可能是删除几个nlargest调用,并在开始时进行一次排序。我不知道缺少所有列,因为缺少示例数据集,但是类似的事情可能起作用:

def f(x):
    x = x.sort_values("recording_date")
    d = {}
    d['fips_2'] = x["fips"].values[0]
    d['apn_2'] = x["apn"].values[0]
    d['most_recent_sale'] = x.sale.iloc[-1]
    d['second_most_recent_sale'] = x.sale.iloc(-2)
    d['third_most_recent_sale'] = x.sale.iloc(-2)
    d['most_recent_price'] = x.price.iloc(-1)
    d['second_most_recent_price'] = x.price.iloc(-2)
    d['third_most_recent_price'] = x.price.iloc(-3)
    d['second_grantor'] = x.seller.iloc(-1)
    d['prior_grantor'] = x.seller.iloc(-2)
    d['type'] = x["type"].values[0]
    return pd.Series(d, index=['apn_2', 'most_recent_sale', 'second_most_recent_sale', 'most_recent_price', 'second_most_recent_price', 'second_grantor', 'type'])

df_grouped = year_past_df.groupby("apn").apply(f)

另一种选择是在整个数据集的开头进行排序,然后使用类似于以下内容的agg函数:

agg_dir = {
    'fips': 'first',
    'sale': ['last', lambda x: x.iloc[-2], lambda x: x.iloc[-3]],
    'price': ['last', lambda x: x.iloc[-2], lambda x: x.iloc[-3]],
    'seller': ['last', lambda x: x.iloc[-2]],
    'type': 'first'
}
df_grouped = year_past_df.sort_values("recording_date").groupby("apn").agg(agg_dir)
df_grouped.columns = ['fips_2', 'most_recent_sale', 'second_most_recent_sale', 
                      'third_most_recent_sale', 'most_recent_price', 'second_most_recent_price', 
                      'third_most_recent_price', 'second_grantor', 'prior_grantor', 'type']