erzn
erzn

Reputation: 13

Import CSV as float in a List (Python 3.5)

I need to import a csv file, which contains about 1.000.000 numbers. they are all separated with decimals (,) so: 1,2,3,4,...

they just ordered easily in the file: no blanks no paragraphs.

This is my actual code:

import statistics
import csv

with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    zahlenliste = list(reader)

print(zahlenliste)

# x = statistics.mean(zahlenliste)
# print(x)

I tried many codes, as on stackoverflow was presented, but I just couldn't execute it without any error.

with all the numbers in the list, i want the arithmetic mean as a result (which is actutally in commentary). with the print(zahlenliste) i wanted to look what the content of the list actually is and looks like:

[['1', '2', '3', '4', '5']]

would you be kind and help me just adding the right function to import the numbers as float to use it in the arithmetic.mean function?

Upvotes: 0

Views: 469

Answers (1)

Finwood
Finwood

Reputation: 3991

The items in your zahlenliste are characters, you'll need to cast them to numbers (int or float). A list comprehension comes in handy here:

zahlenliste = [[int(item) for item in line] for line in reader]

Now you've got a list of lists: The inner lists contain a line's values, the outer list represent the lines. If you need to calculate the mean value for each line, use another list comprehension:

mittelwerte = [statistics.mean(line) for line in zahlenliste]

Upvotes: 2

Related Questions