【问题标题】:CSV reader string to float in pythonCSV阅读器字符串在python中浮动
【发布时间】:2015-04-11 17:38:48
【问题描述】:

我正在使用此函数读取 csv 文件,但我想将其从字符串转换为浮点数。我不确定在哪里插入。当我尝试时,我通常会收到一个错误,即“float”对象没有属性“getitem”

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

【问题讨论】:

  • 您使用什么编程语言?请添加适当的标签。

标签: python string file csv


【解决方案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

【讨论】:

    【解决方案2】:

    我想,您正在使用 Python。你可以简单地将一个String解析为一个float,比如:

    a = "42.23"
    float(a)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-06
      • 2017-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多