0

so i am struggling on understanding converting string to float in python.

i am using a csv file and i want each row of item to be a list, the food name to be a string, the carbs to be a string, and calories to be float

i don't understand how to do that i am trying this:

def menu_list(filep):
    """Function to read the csv file, create a nested list and return the list that is sorted based on calories in the ascending order."""

    menulist = [] #store items
    with open(filep) as csv_file: #read file
        csv_reader = csv.reader (csv_file, delimiter=',')
        next(csv_reader, None)

        mlist = []
        for row in csv_reader:
            row = str
            row[2] = float()
            print (row)

    menulist.sort(key=lambda x: x[1])
    return menulist

every time i run this it give me the error : 'type' object does not support item assignment

can someone help me fix my code and convert string to float?

prvrlx
  • 91
  • 8

2 Answers2

1

You are doing nothing with your csv output. To answer your main question you can use my_float = float(my_str)

In your example, you are asking how to convert an individual column in your csv. This is dependent on your data. Say you have a csv row like this.

"Apple","25 g",95

Since your float is unquoted it's really helpful when parsing the csv. We can simply specify unquoted as numeric in our csv.reader() object.

import csv

def menu_list(filep):
    """
    Function to read the csv file, 
    create a nested list and return the list that is 
    sorted based on calories in the ascending order.
    """

    menulist = [] #store items
    with open(filep) as csv_file: #read file
        csv_reader = csv.reader(csv_file, 
                                delimiter=',', 
                                quotechar='"', 
                                quoting=csv.QUOTE_NONNUMERIC)
        next(csv_reader, None)

        for row in csv_reader:
            menulist.append(row)

    menulist.sort(key=lambda x: x[1])
    return menulist

However, if all or none of your columns in your csv are quoted, you'll have to parse as you're appending

"Apple","25 g","95"

or

Apple,25 g,95
import csv

def menu_list(filep):
    """
    Function to read the csv file, 
    create a nested list and return the list that is 
    sorted based on calories in the ascending order.
    """

    menulist = [] #store items
    with open(filep) as csv_file: #read file
        csv_reader = csv.reader(csv_file, delimiter=',')
        next(csv_reader, None)

        for row in csv_reader:
            row[2] = float(row[2].strip())
            menulist.append(row)

    menulist.sort(key=lambda x: x[1])
    return menulist
Axe319
  • 4,255
  • 3
  • 15
  • 31
  • Is there any way so that it converts float to int if there isn't any decimal point? – user202729 Nov 27 '20 at 04:06
  • (apart from the obvious solution `int(x) if isinstance(x, float) and x.is_integer() else x` (https://stackoverflow.com/questions/6209008/checking-if-float-is-equivalent-to-an-integer-value-in-python) – user202729 Nov 27 '20 at 04:29
0

You can convert string to float easily.

string_num = "555.555"
print(float(string_num)) #It's float now.

If there is non-number your variable, you can use regex. Take a look here

ImC0der
  • 308
  • 2
  • 18
  • i get this one but inside a csv file i need to make the items to be a string the other item to be int and the an item which is a string to be a float – prvrlx May 26 '20 at 12:36