gpt4 book ai didi

python - Pandas:将 Lambda 应用于多个数据帧

转载 作者:太空狗 更新时间:2023-10-30 00:10:28 26 4
gpt4 key购买 nike

我正在尝试找出如何将 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)

最佳答案

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

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

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))

关于python - Pandas:将 Lambda 应用于多个数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31077382/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com