在 pandas 中连接数据帧的最有效方式:loc 或 join?

Most efficient way of joining dataframes in pandas: loc or join?

假设我有两个数据帧;一个持有交易,trans,另一个持有产品信息,prod,我想加入产品价格,变量 price,到交易数据框架,重复它们每一列。以下哪种方法更有效/更受欢迎:

方法一:

trans = trans.set_index('product_id').join(trans.set_index('product_id'))

方法二:

trans.set_index('product_id',inplace=True)
trans['price'] = prod.loc[trans.product_id, 'price']

看来你需要map:

trans = pd.DataFrame({'product_id':[1,2,3],
                   'price':[4,5,6]})

print (trans)
   price  product_id
0      4           1
1      5           2
2      6           3

prod = pd.DataFrame({'product_id':[1,2,4],
                   'price':[40,50,60]})

print (prod)
   price  product_id
0     40           1
1     50           2
2     60           4

d = prod.set_index('product_id')['price'].to_dict()
trans['price'] = trans['product_id'].map(d)
print (trans)
   price  product_id
0   40.0           1
1   50.0           2
2    NaN           3