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