我如何在某些附加条件下对数据框执行vlookup等效操作 [英] how do I perform a vlookup equivalent operation on my dataframe with some additional conditions

查看:64
本文介绍了我如何在某些附加条件下对数据框执行vlookup等效操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在python上运行查找等效函数,但是尝试合并和加入时我还没有触手可及.

HI I am trying to run lookup equivalent function on python but having tried merge and join I haven't hit the nail yet.

所以我的第一个df是这个

so my first df is this

list = ['Computer', 'AA', 'Monitor', 'BB', 'Printer', 'BB', 'Desk', 'AA', 'Printer', 'DD', 'Desk', 'BB']
list2 = [1500, 232, 300, 2323, 150, 2323, 250, 2323, 23, 34, 45, 56]
df = pd.DataFrame(list,columns=['product'])
df['number'] = list2

这是df的外观

     product  number
0   Computer   1500
1         AA    232
2    Monitor    300
3         BB   2323
4    Printer    150
5         BB   2323
6       Desk    250
7         AA   2323
8    Printer     23
9         DD     34
10      Desk     45
11        BB     56

这是第二个数据帧

list_n = ['AA','BB','CC','DD']
list_n2 = ['Y','N','N','Y']

df2 = pd.DataFrame(list_n,columns=['product'])
df2['to_add'] = list_n2

这是df2的外观

  product to_add
0      AA      Y
1      BB      N
2      CC      N
3      DD      Y

现在,如何将列('to_add')添加到第一个数据帧(df),所以它看起来应该像这样.在excel中,它是一个简单的vlookup.我尝试了'merge'和'join'函数,但是它改变了我df的顺序,我不想改变顺序.有什么想法吗?

Now, how do I add a column ('to_add') to the first dataframe (df) so it should look a bit like this. In excel its a simple vlookup. I tried 'merge' and 'join' functions but its altering the sequence of my df and I don't want the sequencing to change. any ideas?

     product  price to_add
0   Computer   1500       
1         AA    232      Y
2    Monitor    300       
3         BB   2323      N
4    Printer    150       
5         BB   2323      N
6       Desk    250       
7         AA   2323      Y
8    Printer     23       
9         DD     34      Y
10      Desk     45       
11        BB     56      N

推荐答案

pd.merge确实可以完成工作,可能您没有正确使用它:

pd.merge indeed will do the job, probably you were not using it correctly:

pd.merge(df, df2, on="product", how="left")

将返回:

     product  number to_add
0   Computer    1500    NaN
1         AA     232      Y
2    Monitor     300    NaN
3         BB    2323      N
4    Printer     150    NaN
5         BB    2323      N
6       Desk     250    NaN
7         AA    2323      Y
8    Printer      23    NaN
9         DD      34      Y
10      Desk      45    NaN
11        BB      56      N

这篇关于我如何在某些附加条件下对数据框执行vlookup等效操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆