python csv DictReader 类型

8 投票
4 回答
12621 浏览
提问于 2025-04-17 09:37

我刚开始学习用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()

我不想一个一个地转换每个值。有没有办法定义列的值类型呢?

4 个回答

1

我之前没用过DictReader,不过你可以这样处理值:

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

然后在后面的代码中用col1,你也可以修改这个字典:

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

不过这要看你后面想怎么用这一行数据。

6

如果你在csv文件中把非数字的值用引号括起来,并且用下面的方式初始化读取器

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

那么数字值会自动转换成浮点数。

9

你可以使用像pandas这样的库,它会自动推断数据的类型(虽然有点大材小用,但确实能完成任务)。

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}]

撰写回答