Search code examples
pythonpandasdata-analysis

Using a Pandas DataFrame as Lookup


I have 2 pandas DataFrames, this one:

item    inStock     description  
Apples    10        a juicy treat
Oranges   34        mediocre at best
Bananas   21        can be used as phone prop
<...many other fruits...>
Kiwi       0        too fuzzy

and a lookup table with only a subset of the items above:

item     Price
Apples   1.99
Oranges  6.99

I would like to scan through the first table and fill in a price column for the DataFrame when the fruit in the first DataFrame matches the fruit in the second:

item    inStock     description                   Price
Apples    10        a juicy treat                 1.99
Oranges   34        mediocre at best              6.99
Bananas   21        can be used as phone prop
<...many other fruits...>
Kiwi       0        too fuzzy

I've looked at examples with the built-in lookup function, as well as using a where-in type function but I cannot seem to get the syntax to work. Can someone help me out?


Solution

  • import pandas as pd
    
    df_item= pd.read_csv('Item.txt')
    df_price= pd.read_csv('Price.txt')
    
    df_final=pd.merge(df_item,df_price ,on='item',how='left' )
    print df_final
    

    output

          item  inStock                description  Price
    0   Apples       10              a juicy treat   1.99
    1  Oranges       34           mediocre at best   6.99
    2  Bananas       21  can be used as phone prop    NaN
    3     Kiwi        0                  too fuzzy    NaN