在Python Pandas中保存重复的计算

时间:2017-12-08 04:04:43

标签: python pandas

在Pandas中,我可以使用.apply将函数应用于两列。例如,

df = pd.DataFrame({'A':['a', 'a', 'a', 'b'], 'B':[3, 3, 2, 5], 'C':[2, 2, 2, 8]})
formula = lambda x: (x.B + x.C)**2
df.apply(formula, axis=1)

但是,请注意前两行的结果是相同的,因为所有输入都是相同的。在具有复杂操作的大型数据集中。这些重复计算可能会减慢我的程序。有没有办法可以对它进行编程,以便我可以通过这些重复计算节省时间?

2 个答案:

答案 0 :(得分:2)

您可以使用名为memoization的技术。对于接受hashable参数的函数,您可以使用内置的functools.lru_cache

from functools import lru_cache

@lru_cache(maxsize=None)
def cached_function(B, C):
    return (B + C)**2

def formula(x):
    return cached_function(x.B, x.C)

请注意,我必须将值传递给lru_cache的缓存函数才能正常工作,因为Series对象不可用。

答案 1 :(得分:0)

您可以使用np.unique创建仅包含唯一行的数据框副本,然后对其进行计算,并构建完整结果。

例如:

import numpy as np

# convert to records for use with numpy
rec = df.to_records(index=False)
arr, ind = np.unique(rec, return_inverse=True)

# find dataframe of unique rows
df_small = pd.DataFrame(arr)

# Apply the formula & construct the full result
df_small.apply(formula, axis=1).iloc[ind].reset_index()

这比使用apply更快就是使用广播:例如,简单地计算

(df.B + df.C) ** 2

如果这仍然太慢,您可以在重复数据删除的数据帧上使用此方法,如上所述。