[英]Pandas Apply Function Slow Speed
我有一個正在運行 apply() 函數的數據框(大約 1 - 3 M 條記錄)。 這需要相當長的時間。 我已經閱讀了一些不應該使用 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)
有沒有更好的方法來完成相同的任務,但速度更快?
一種改進可能是刪除幾個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']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.