【问题标题】:Most efficient way of joining dataframes in pandas: loc or join?在 pandas 中加入数据框的最有效方法:loc 还是 join?
【发布时间】:2017-08-06 03:31:48
【问题描述】:

假设我有两个数据框;一个保存交易,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']

【问题讨论】:

  • 不确定您在方法 1 中要做什么
  • 你能添加一些数据样本吗?

标签: python pandas join pandas-loc


【解决方案1】:

看来你需要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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 2023-02-25
    • 2023-02-08
    • 2018-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多