0

I have a csv file that has 3 column (product name, price, website).

product.csv

Product_name,price, website
Koko krunch,13.99,Lotus
Koko krunch,15.90,mygroser
Koko krunch,15.49,gogopasar

How do I compare the price and then display the lowest price with the product name and website? Below is my code but the result is not accurate and I think there's a better way to do it.

import pandas as pd

data = pd.read_csv("product_list.csv")
df = pd.DataFrame(data, columns= ['price'])
df = df.astype(float)

temp_product = []
temp_price = []
temp_website = []

for i in data.loc[:,'product_name']:
    temp_product.append(i)

for i in df.loc[:,'price']:
    temp_price.append(i)

for i in data.loc[:,'website']:
    temp_website.append(i)


prices = 9999.99
temp = 0

for i in temp_price:    
    if i<prices:    
        index = temp
    temp+=1

print("")        
print("Product with lowest price:")
print("") 
print("PRODUCT: " + temp_product[index])  
print("PRICE: RM " , temp_price[index])  
print("WEBSITE: " + temp_website[index])
print("") 

The output of this code is PRODUCT: Koko krunch Price: RM 15.40 Website: gogopasar

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • Please provide a brief sample of the data (with header) in your example, and explain what output you're getting from that example data, as well as what you expected / needed as output. (and provide it in the edited question, not in the comments) – Grismar Jul 25 '22 at 21:47
  • Apart from that, your code raises many questions. Why are you moving around data to lists when you already have a DataFrame? You could probably solve the whole problem in a single line using a pandas DataFrame? Why set columns to be `['price']` when you say there's three columns? – Grismar Jul 25 '22 at 21:49

2 Answers2

0

If you want to find minimum price row, you can use idxmin() function:

import pandas as pd
df = pd.DataFrame(data={'a':[5,3,6,1,4], 'b':['Achi', 'Bichi', 'Giorguna', 'Ar', 'Gaushva']})
result = df.loc[df.a.idxmin()]
print(result)

Output:

a     1
b    Ar
Name: 3, dtype: object

You can find more details here

Zorojuro
  • 71
  • 5
0

Ordinarily, I wouldn't respond to homework, but you are so far off the mark here that I think you need help.

You don't need to convert to another dataframe. read_csv returns one to you. You don't need to iterate through the rows. Pandas can tell you the minimum value directly, and you can use that to select the row you need:

import pandas as pd
data = pd.read_csv("product_list.csv")
print(data[data.price == data.price.min()])

Notice how that last line reads. That says "give me the row(s) in data in which the price field equals the minimum of the price column.

Output:

  Product_name  price  website
0  Koko krunch  13.99    Lotus
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30