how do I perform a vlookup equivalent operation on my dataframe with some additional conditions

扶醉桌前 提交于 2021-02-11 13:58:39

问题


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

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

This is how the df would look

     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

This is the 2nd dataframe

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

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

This is how df2 looks like

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

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

回答1:


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

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

will return:

     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


来源:https://stackoverflow.com/questions/61513874/how-do-i-perform-a-vlookup-equivalent-operation-on-my-dataframe-with-some-additi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!