问题
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