熊猫:将Lambda应用于多个数据框架

jtr*_*dge 6 python memory lambda dataframe pandas

我试图找出如何同时将lambda函数应用于多个数据帧,而无需先将数据帧合并在一起.我正在处理大型数据集(> 60MM记录),我需要特别注意内存管理.

我希望有一种方法可以将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)
Run Code Online (Sandbox Code Playgroud)

art*_*igo 5

我知道这个问题有点老了,但这是我想出的一种方法。这不是很好,但是很有效。

基本思想是查询应用函数内的第二个数据帧。通过使用传递的系列的名称,您可以识别列/索引并使用它从其他数据帧检索所需的值。

def func(x, other):
    other_value = other.loc[x.name]
    return your_actual_method(x, other_value)

result = df1.apply(lambda x: func(x, df2))
Run Code Online (Sandbox Code Playgroud)


Ale*_*der 1

一种选择是显式创建所需的聚合:

theSum = df1.A + df1.B
theAverage = (df1.A + df1.B + df2.C + df3.D) / 4.
theProduct = df1.B * df2.C * df3.D
theResult = pd.concat([theSum, theAverage, theProduct])
theResult.columns = ['Sum', 'Average', 'Product']
Run Code Online (Sandbox Code Playgroud)

另一种可能性是使用query,但这实际上取决于您的用例以及您打算如何聚合数据。以下是可能适用于您的文档的示例。

map(lambda frame: frame.query(expr), [df, df2])
Run Code Online (Sandbox Code Playgroud)