【问题标题】:python csv DictReader typepython csv DictReader 类型
【发布时间】:2023-03-26 22:00:01
【问题描述】:

我开始在 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()

我不会转换每一个值。是否可以定义列的值?

【问题讨论】:

    标签: python types csv


    【解决方案1】:

    您可以使用 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}]
    

    【讨论】:

      【解决方案2】:

      我之前没有使用过 DictReader,但您可以对值执行此操作:

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

      然后用 col1 遍历出来,你可能还可以编辑字典:

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

      但这取决于您以后要使用该行的内容。

      【讨论】:

        【解决方案3】:

        如果你引用 csv 文件中的非数字值并通过

        初始化阅读器
        pol = csv.DictReader(open('..\data\data.csv'),
            quoting=csv.QUOTE_NONNUMERIC, dialect="excel")
        

        然后数值将自动转换为浮点数。

        【讨论】:

        • 不幸的是,这仍然会扼杀标题。
        【解决方案4】:

        看起来您希望 Col1 是一个数字数组,因此无论您是否将其与数字进行比较,都需要将 row["Col1"] 转换为数字。所以转换它!

        【讨论】:

          猜你喜欢
          • 2011-12-14
          • 2010-11-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-01-27
          • 1970-01-01
          • 2020-11-06
          • 2011-06-27
          相关资源
          最近更新 更多