Python 基于两列值从数据帧中高效提取信息

Python 基于两列值从数据帧中高效提取信息,python,pandas,Python,Pandas,我试图从一个由productId和customerId索引的数据帧中提取信息。我有大量(数百万)对(productId、customerId),我有兴趣找到最有效的方法来实现这一点 我有两个数据帧,df1包含我感兴趣的customerId和productId对,第二个帧df2包含由customerId和productId对索引的感兴趣的信息 到目前为止,我已经尝试过以下方法: def f(x, y): return(df2.col[(df2.customerId == x) &

我试图从一个由productId和customerId索引的数据帧中提取信息。我有大量(数百万)对(productId、customerId),我有兴趣找到最有效的方法来实现这一点

我有两个数据帧,df1包含我感兴趣的customerId和productId对,第二个帧df2包含由customerId和productId对索引的感兴趣的信息

到目前为止,我已经尝试过以下方法:

def f(x, y):
    return(df2.col[(df2.customerId == x) & (df2.productId == y)].sum())

values = df1.apply(lambda x: f(x.customerId, x.productId), axis = 1)
它工作正常,但速度很慢


有任何改进建议吗?

您可以尝试列表理解:

values = [df2.loc[df2[['customerId', 'productId']].eq(i).all(), 'col'].sum() for i in df1.values]

您可以尝试以下列表:

values = [df2.loc[df2[['customerId', 'productId']].eq(i).all(), 'col'].sum() for i in df1.values]

我尝试了这个方法,但速度稍微慢了一点——200行14.7秒,而原始方法是13.7秒。谢谢您的意见。@ConorMcCabe编辑过,请再试一次again@d-n-n编辑again@d-n-n编辑againOK,如果完整的真实数据更快,请告诉我,我会投票给答案。我尝试了这个方法,但速度稍慢-200行14.7秒,而原始方法为13.7秒。谢谢您的意见。@ConorMcCabe编辑过,请再试一次again@d-n-n编辑again@d-n-n编辑againOK,如果更快的完整真实数据让我知道,我会投票回答。