基于两个列值从熊猫数据框中有效提取信息

问题描述 投票:1回答:1

我正在尝试从由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)

效果很好,但是非常慢。

有什么改进建议吗?

python pandas
1个回答
0
投票

您可以尝试使用列表理解:

values = [df2.loc[df2[['customerId', 'productId']].eq(i).all(), 'col'].sum() for i in df1.values]
© www.soinside.com 2019 - 2024. All rights reserved.