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
CodePudding user response:
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
CodePudding user response:
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