Leo
Leo

Reputation: 1

How to change multiple str to float in a file and then average the total without getting errors?

I am very new to coding so please elaborate and use examples to explain. I have a text file that has many numbers along with names and other str. I need to know how i can convert the numbers that are currently str into floats so i can calculate the average.

I have tried using the str as floats but i get error TypeError: unsupported operand type(s) for +: 'int' and 'str' which is expected

i have also tried setting the str to float but it gives me

Traceback (most recent call last): File "C:\Users\leona\Desktop\School Work\moretesting.py", line 9, in average = sum(num1) / len(num1) TypeError: 'float' object is not iterable

file = input("Enter a filename: ")

with open(file, "r") as f:

   next(f)

   for line in f:

       lines = line.split(",")

       num1 = float(lines[6])

       average = sum(num1) / len(num1)

       print(average)

The file has this inside (just a portion of the text file because its way to big but i just need to understand how to do this type of problem):

zip,eiaid,utility_name,state,service_type,ownership,comm_rate,ind_rate,res_rate
52346,9417,Interstate Power and Light Co,IA,Bundled,Investor Owned,0.0922343168969,0.0589686412318,0.130070934252
72424,814,Entergy Arkansas Inc,AR,Bundled,Investor Owned,0.0735129328027,0.0594501735324,0.0908957415387


Traceback (most recent call last):
  File "C:\Users\leona\Desktop\School Work\moretesting.py", line 9, in <module>
    average = sum(num1) / len(num1)
TypeError: 'float' object is not iterable

Upvotes: 0

Views: 64

Answers (1)

razdi
razdi

Reputation: 1440

You can append the values in that column to a list and then get the average of the list as follows:

file = input("Enter a filename: ")

with open(file, "r") as f:

  next(f)
  num_list = []

  for line in f:
    lines = line.split(",")
    num_list.append(float(lines[6])

  average = sum(l) / float(len(l))
  print(average)

Upvotes: 0

Related Questions