python csv DictReader类型 [英] python csv DictReader type

查看:699
本文介绍了python csv DictReader类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始使用python进行编码,现在我遇到了问题,即csv.DictReader会为我提供错误的数据类型.

I'm starting to code in python and i now have the problem, that the csv.DictReader gets me the wrong data type.

csv文件如下:

Col1,Col2,Col3

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 won't convert every single value. Is it possible to define the values of the column?

推荐答案

您可以使用像pandas这样的库,它将为您推断类型(虽然有点过头,但确实可以完成工作).

You could use a library like pandas, it will infer the types for you (it's a bit of an overkill but it does the job).

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的实现:

Alternatively here is an implementation of a typed 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}]

这篇关于python csv DictReader类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆