2016-11-15 78 views
3

我想讀一個CSV文件作爲這樣一個矩陣:如何將csv文件中的字符串列表轉換爲浮點型?

import csv 
with open("data.csv", "r") as file: 
    table = [line for line in csv.reader(file)] 
    for line in table: 
     print(line) 

但是,我需要在列表中的內容轉換爲浮動。我試圖轉換使用

table = [int(x) for x in table] 

浮動然而這出來作爲一個錯誤

TypeError: int() argument must be a string or a number, not 'list'

怎樣才能解決這個問題?

+1

int(e)for e in lst –

+0

請修復您的代碼格式 – inspectorG4dget

回答

1

下面是一個簡單的例子,如何在每一行數據轉換爲float數值類型,並做一些計算:

假設CSV數據文件data.csv充滿了一些intsfloats

12,13,14,15,16 
0.1,0.2,0.3,0.4,0.5 
import csv 
with open("./data.csv", "rU") as file: 
    table = [line for line in csv.reader(file)] 
    for line in table: 
     numbers = [ float(x) for x in line ] 
     sum = 0 
     for number in numbers: 
      sum = sum + number 
     print(numbers) 
     print "The sum of numbers is: ", sum 

OUPUTS:

[12.0, 13.0, 14.0, 15.0, 16.0] 
The sum of numbers is: 70.0 
[0.1, 0.2, 0.3, 0.4, 0.5] 
The sum of numbers is: 1.5 
相關問題