如何使用vlookup函数向具有多索引列的数据帧添加列?

2024-09-24 22:25:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试找出如何从该数据帧添加列: enter image description here

对于这一点:

enter image description here

正如你们所看到的,两个数据帧都有“SPU”列,所以需要根据这个列添加数据(比如vlookup函数)。问题在于第二个数据帧具有多索引列,因此:

pv = pd.merge(dataframe1,dataframe2[['SPU','Adv_per_unit']],on = 'SPU',how='left')

它不起作用

我试图通过添加以下内容来解决这一问题:

dataframe1['Ads', 'Adv_per_unit'] = dataframe2['Adv_per_unit']

但很明显,这并不能解决问题,因为“每单位Adv_”中的数据与dataframe2中的数据不匹配,因为它没有正确合并

另外,我检查了许多已经存在的关于stackoverflow的类似主题,但是没有找到一个解决方案来解决需要使用vlookup函数添加数据的情况

enter image description here


Tags: 数据函数onunitmergelefthowpd
1条回答
网友
1楼 · 发布于 2024-09-24 22:25:11

如果SPU条目是唯一的,则可以将该列用作索引,然后运行

dataframe1['Ads', 'Adv_per_unit'] = dataframe2['Adv_per_unit']

编辑:扩展答案

要将SPU设置为索引,应运行:

dataframe1.set_index("SPU", inplace=True)
dataframe2.set_index("SPU", inplace=True)

相关问题 更多 >