【问题标题】:How to speed up successive pd.apply with successive pd.DataFrame.loc calls?如何通过连续的 pd.DataFrame.loc 调用加速连续的 pd.apply?
【发布时间】:2021-06-10 14:42:26
【问题描述】:
def __link_price(row: pd.Series) -> Union[None, float]:
    if (row['fund'] == 'A') and (row['share_class'] == 'X'):
        return df_hist.loc[row['date'], 'AA']
    elif (row['fund'] == 'A') and (row['share_class'] == 'Y'):
        return df_hist.loc[row['date'], 'AB']
    elif (row['fund'] == 'B') and (row['share_class'] == 'X'):
        return df_hist.loc[row['date'], 'BA']
    elif (row['fund'] == 'B') and (row['share_class'] == 'Y'):
        return df_hist.loc[row['date'], 'BB']
    elif (row['fund'] == 'C') and (row['share_class'] == 'X'):
        return df_hist.loc[row['date'], 'CA']
    elif (row['fund'] == 'C') and (row['share_class'] == 'Y'):
        return df_hist.loc[row['date'], 'CB']
    else:
        return 0

df.loc[:, 'price'] = df.apply(__link_price_at_purchase, axis=1).values

df 有 10,000+ 行,所以这段代码需要很长时间。除了每一行,我都在调用df_hist.loc 来获取值。

我正在尝试加快这部分代码的速度,然后我目前发现的选项正在使用:

df.loc[:, 'price'] = df.apply(__link_price_at_purchase, axis=1, raw=True).values

但这迫使我对row 使用基于索引的选择而不是值选择:

if (row[0] == 'A') and (row[1] == 'X')

这会降低代码的可读性。

我正在寻找一种既能加快代码速度又能提高代码可读性的方法。

【问题讨论】:

  • 我会将调用链接到np.where
  • 如果你有多个if/else条件,则使用np.select,否则使用np.where。
  • 也就是说,这些数据帧的格式是什么?也许你可以改用merge_asof
  • 问题是第二个数据框列和行选择取决于第一个数据框行的值,因此无法合并。
  • 索引和df['date']一样吗?

标签: python pandas dataframe performance optimization


【解决方案1】:

在 python 中,每个属性或项的查找和函数调用都有一些成本。而且您没有为您优化事物的编译器。

以下是一些一般性建议:

  1. 尝试在不使用 Python 函数的情况下创建包含 fund 和 share_class 的列,然后将其与 df_hist 合并
# convert history from 'wide' format into 'long' format
hist = df_hist.set_index("date").stack()
prices = (
    # create key column for join
    df.assign(key=df["fund"] + df["share_class"].replace({"X": "A", "Y": "B"}))
    .set_index(["date", "key"])
    .join(hist)  # join by index
)
  1. 如果创建key 列并非易事,请尽量减少apply 函数内的属性查找:
def __link_price(row):
    date, fund, share_class = row[["date", "fund", "share_class"]]
    
    if fund == 'A' and share_class == 'X':
        return df_hist.loc[date, 'AA']
    ...
  1. 优化 if 条件。例如,(row['fund'] == 'C') and (row['share_class'] == 'Y') 需要检查 6 个条件。您可以将此数字最小化为 ... 1。
fund_and_share_class_to_key = {
    ("A", "X"): "AA",
    ("A", "Y"): "AB",
    ...
}

key = fund_and_share_class_to_key.get((fund, share_class))
return df_hist.loc[date, key] if key is not None else 0
  1. Pandas 本身对于非矢量化和非算术运算非常慢。在您的情况下,最好使用标准 python dicts 来加快查找速度。
# small benchmark
df = pd.DataFrame({"value": [4,5,6]})
d = df.to_dict(orient="index")
%timeit df.loc[1, "value"]  # 8.7ms
%timeit d[1]["value"]       # 50ns; ~170 times faster
# convert dataframe into the dict with format:
# {<date>: {"AA": <value>}}
history = df_hist.set_index("date").to_dict(orient="index")

def __link_price(row):
    ...
    price = history.get(date, {}).get(key, 0)
    return price
  1. 将历史记录作为应用参数传递应该比在非本地范围内搜索要快。它还使代码更简洁。
def __link_price(row, history):
    ...
df.apply(__link_price, args=(history, ))

总而言之,一个更快的函数应该是这样的:

history = df_hist.set_index("date").to_dict(orient="index")
# we don't need to create a mapping on every __link_price call
fund_and_share_class_to_key = {
    ("A", "X"): "AA",
    ("A", "Y"): "AB",
    ...
}
def __link_price(row, history, fund_and_share_class_to_key):
    date, fund, share_class = row[["date", "fund", "share_class"]]
    key = fund_and_share_class_to_key.get((fund, share_class))
    return history.get(date, {}).get(key, 0)

df.apply(__link_price, args=(history, fund_and_share_class_to_key))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多