Home > OS >  How do I compare values within a column in a csv file in python?
How do I compare values within a column in a csv file in python?

Time:07-24

I have a csv file that contain product data. It has 3 column which are product_name, price and website.

Below is my code. I want to get the lowest price in python but I am not sure which part I did wrong.

import pandas as pd

data = pd.read_csv("product_list.csv")
df = pd.DataFrame(data, columns= ['price'])
df['price'] = pd.to_numeric(df['price'], errors='coerce')

prices = 99
temp = []

for i in df:
    temp.append(df.price)

for i in temp:
    if temp[i]<prices:
        prices = temp[i]       

print(prices)

The error state "TypeError: list indices must be integers or slices, not Series"

CodePudding user response:

There is at least 2 mistake i can spot on your code. The first and second loop

I believe at the first loop you want to append price of each row on df, this is the way to do it (tell me if im wrong)


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

Another way to iterate through rows on a dataframe: How to iterate over rows in a DataFrame in Pandas

Then, at the second loop it should be like this.


for i in temp:
    if i<prices:
        prices = i  

I suggest you learn more about For loop in python :)

  • Related