PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 28, 2022

[FIXED] How do I compare values within a column in a csv file in python?

 August 28, 2022     csv, pandas, python     No comments   

Issue

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"


Solution

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 :)



Answered By - zousan
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing