我正在尝试找出如何同时将lambda函数应用于多个数据框,而无需先将它们合并。我正在处理大型数据集(> 60MM记录),因此需要特别注意内存管理。
我的希望是,有一种方法可以将lambda应用于基础数据框架,以便我可以避免首先将它们拼接在一起的成本,然后在进行下一步处理之前从内存中删除该中间数据框。
我通过使用基于HDF5的数据框架来规避内存问题,但我更愿意首先尝试探索不同的解决方案。
我提供了一个玩具问题来帮助说明我的意思。
我的希望是,有一种方法可以将lambda应用于基础数据框架,以便我可以避免首先将它们拼接在一起的成本,然后在进行下一步处理之前从内存中删除该中间数据框。
我通过使用基于HDF5的数据框架来规避内存问题,但我更愿意首先尝试探索不同的解决方案。
我提供了一个玩具问题来帮助说明我的意思。
import numpy as np
import pandas as pd
# Here's an arbitrary function to use with lambda
def someFunction(input1, input2, input3, input4):
theSum = input1 + input2
theAverage = (input1 + input2 + input3 + input4) / 4
theProduct = input2 * input3 * input4
return pd.Series({'Sum' : theSum, 'Average' : theAverage, 'Product' : theProduct})
# Cook up some dummy dataframes
df1 = pd.DataFrame(np.random.randn(6,2),columns=list('AB'))
df2 = pd.DataFrame(np.random.randn(6,1),columns=list('C'))
df3 = pd.DataFrame(np.random.randn(6,1),columns=list('D'))
# Currently, I merge the dataframes together and then apply the lambda function
dfConsolodated = pd.concat([df1, df2, df3], axis=1)
# This works just fine, but merging the dataframes seems like an extra step
dfResults = dfConsolodated.apply(lambda x: someFunction(x['A'], x['B'], x['C'], x['D']), axis = 1)
# I want to avoid the concat completely in order to be more efficient with memory. I am hoping for something like this:
# I am COMPLETELY making this syntax up for conceptual purposes, my apologies.
dfResultsWithoutConcat = [df1, df2, df3].apply(lambda x: someFunction(df1['A'], df1['B'], df2['C'], df3['D']), axis = 1)