How can i make vlookup like in excel to pandas, i'm totally begginer in python. My first and second dataframe like this
data_01 = pd.DataFrame({'Tipe Car':['A', 'B', 'C', 'D'], 'Branch':['UD', 'UA', 'UK', 'UA'], 'Area':['1A', '1B', '1C', '1D']})
data_02 = pd.DataFrame({'Tipe Car':['A', 'B', 'E', 'F'], 'Branch':['UD', 'UA', 'UK', 'UA']})
and then expected output is
data_03 = pd.DataFrame({'Tipe Car':['A', 'B', 'E', 'F'], 'Branch':['UD', 'UA', 'UK', 'UA'], 'Area':['1A', '1B', 'NaN', 'NaN']})
CodePudding user response:
import pandas as pd
df1 = pd.DataFrame({'Tipe Car':['A', 'B', 'C', 'D'], 'Branch':['UD', 'UA', 'UK', 'UA'], 'Area':['1A', '1B', '1C', '1D']})
df2 = pd.DataFrame({'Tipe Car':['A', 'B', 'E', 'F'], 'Branch':['UD', 'UA', 'UK', 'UA']})
df1.set_index('Tipe Car').join(df2.set_index('Tipe Car'), how='right', lsuffix='_df1', rsuffix='_df2')
>>>
Branch_df1 Area Branch_df2
Tipe Car
A UD 1A UD
B UA 1B UA
E NaN NaN UK
F NaN NaN UA
CodePudding user response:
You could use .merge()
:
data_03 = data_02.merge(data_01, on=["Tipe Car", "Branch"], how="left")
Result:
Tipe Car Branch Area
0 A UD 1A
1 B UA 1B
2 E UK NaN
3 F UA NaN