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

特罗布里奇

我试图弄清楚如何将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)
亚力山大

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

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']

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

map(lambda frame: frame.query(expr), [df, df2])

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章