2015-02-11 185 views
0

我正在使用此函數來讀取一個csv文件,但我想將它從字符串轉換爲浮動。我不確定在哪裏插入。當我嘗試我通常拿到「浮動」對象有沒有屬性「的GetItem」CSV閱讀器字符串浮在python

def getColumn(filename, column): 
    results = csv.reader(open(filename), delimiter=',') 
    next(results, None) 
    return [result[column] for result in results] 
+1

什麼編程語言是您使用?請添加適當的標籤。 – user1438038 2015-02-11 11:11:07

回答

1
import csv 

def get_column(filename, column): 
    with open(filename) as f: 
     reader = csv.DictReader(f) 
     results = [] 

     for row in reader: 
      entry = row[column] 

      try: 
       results.append(float(entry)) 
      except ValueError: 
       print(
        "Could not convert '{}' to " 
        "a float...skipping.".format(entry) 
       ) 

     return results 

result = get_column('csv.csv', 'num') 

print(result) 
print(sum(result)) 


--output:-- 
Could not convert 'mars' to a float...skipping. 
[3.1, 2.6] 
5.7 
0

我想一個錯誤,您正在使用Python。你可以簡單地解析字符串爲float,如:

a = "42.23" 
float(a)