首页 > 解决方案 > Python VLookup get output without merge

问题描述

I have 2 data sets,and I need to get the 'MAKE' column based on the 'MODEL' but the results column in a separate dataframe (Not merge with existing dataframe)

I could merge the data by using below code,

def vlookup_sample():

    df1 = pd.read_excel('tb1.xlsx', sheet_name='Sheet1')
    df2 = pd.read_excel('tb2.xlsx', sheet_name='Sheet1')

    df = pd.merge(df1, df2[['MODEL', 'MAKE']], on='MODEL', how='left')
    df["MAKE"].fillna("<n/a>", inplace=True)

    print df

Dataset 1

ID  MODEL   REQUESTS    ORDERS
1   Golf    123          4
2   Passat  34           5
3   Model 3 500          8
4   M3      5            0

Dataset2

MODEL   TYPE    MAKE
Golf    Sedan   Volkswagen
M3      Coupe   BMW
Model 3 Sedan   Tesla

Expected output:

MAKE
 Volkswagen
 Nan
 Tesla
BMW

How do I get the result in to a separate data

标签: pythonexcelpandasdataframevlookup

解决方案


您可以使用以下方法进行相同的合并并MAKE从合并输出中调用该列df.loc[]

new_df = df1.merge(df2,on='MODEL',how='left').loc[:,['MAKE']]
#pd.merge(df1, df2[['MODEL', 'MAKE']], on='MODEL', how='left').loc[:,['MAKE']]

推荐阅读