2012-01-05 60 views
3

我開始在python中編寫代碼,現在我遇到了問題,即csv.DictReader使我得到了錯誤的數據類型。python csv DictReader類型

CSV文件看起來像:

Col1中,col2的,COL3

1,2,3

90,2,3

pol = csv.DictReader(open('..\data\data.csv'),dialect='excel') 

Col1 = [] 

for row in pol: 
    if row["Col1"] < 90: 
     Col1.append(row["Col1"] * 1.5) 
    else: 
     Col1.append("Col1") 

我得到以下錯誤:

if row["Col1"] < 90: 
TypeError: unorderable types: str() < int() 

I將不會轉換每一個值。是否可以定義列的值?

回答

0

看起來您希望Col1是一個數字數組,因此您需要將行[「Col1」]轉換爲數字,無論您是否將其與數字進行比較。所以轉換它!

2

如果您引用非數字值的CSV文件,並通過

pol = csv.DictReader(open('..\data\data.csv'), 
    quoting=csv.QUOTE_NONNUMERIC, dialect="excel") 

那麼數值將被自動轉換爲浮動初始化讀者。

+0

不幸的是,這仍然會窒息頭。 – 2012-01-05 19:52:08

+0

正是我在找什麼,謝謝! – MoRe 2014-12-08 18:06:48

1

我以前沒有使用過DictReader,但你可能只是這樣做的價值:

... 
for row in pol: 
    col1 = float(row["Col1"]) # or int() 
    ... 

然後通過出使用COL1,你或許也可以編輯詞典:

row["Col1"] = float(row["Col1"]) 

但是,這取決於您想要以後使用該行的內容。

7

你可以使用像熊貓這樣的圖書館,它會推斷你的類型(這有點矯枉過正,但它的工作)。

import pandas 
data = pandas.read_csv(r'..\data\data.csv') 
# if you just want to retrieve the first column as a list of int do 
list(data.Col1) 
>>> [1, 90] 

# to convert the whole CSV file to a list of dict use 
data.transpose().to_dict().values() 
>>> [{' Col2': 2, ' Col3': 3, 'Col1': 1}, {' Col2': 2, ' Col3': 3, 'Col1': 90}] 

另外這裏是一個類型DictReader的實現:

from csv import DictReader 
from itertools import imap, izip 

class TypedDictReader(DictReader): 
    def __init__(self, f, fieldnames=None, restkey=None, restval=None, \ 
     dialect="excel", fieldtypes=None, *args, **kwds): 

    DictReader.__init__(self, f, fieldnames, restkey, restval, dialect, *args, **kwds) 
    self._fieldtypes = fieldtypes 

    def next(self): 
    d = DictReader.next(self) 
    if len(self._fieldtypes) >= len(d) : 
     # extract the values in the same order as the csv header 
     ivalues = imap(d.get, self._fieldnames) 
     # apply type conversions 
     iconverted = (x(y) for (x,y) in izip(self._fieldtypes, ivalues)) 
     # pass the field names and the converted values to the dict constructor 
     d = dict(izip(self._fieldnames, iconverted)) 

    return d 

,這裏是如何使用它:

reader = TypedDictReader(open('..\data\data.csv'), dialect='excel', \ 
    fieldtypes=[int, int, int]) 
list(reader) 
>>> [{' Col2': 2, ' Col3': 3, 'Col1': 1}, {' Col2': 2, ' Col3': 3, 'Col1': 90}]