【问题标题】:How to convert csv string to float? [duplicate]如何将csv字符串转换为浮点数? [复制]
【发布时间】:2020-12-11 07:11:11
【问题描述】:

我有 export.csv 文件,里面有数据

name,total
candy,10
ice cream,15
potatoe chips,20 

当我使用此代码读取 .csv 文件时

with open('files/export.csv','r') as file_csv:
    read= list(csv.reader(file_csv))
    for row in read:
        print(row)

原来total列中的数据是字符串数据类型而不是浮点数。我希望输出是这样的:

"name","total"
"candy",10
"ice cream",15
"potatoe chips",20

所以我可以求和并获取总列数据。

【问题讨论】:

  • float 内置函数可以将字符串转换为浮点数,只要它是 Python 的字面浮点格式。

标签: python csv


【解决方案1】:

要将第二个字段转换为floats,以下应该适合您:

import csv

with open('files/export.csv','r') as file_csv:
    read = list(csv.reader(file_csv))
    for i, row in enumerate(read):
        if i > 0:
            row[1] = float(row[1])
        print(row)

请注意,在这里,我们必须跳过第一行(标题)以仅将转换应用于数据本身。

【讨论】:

    【解决方案2】:

    尝试用 pandas 来阅读。对 csv 文件给予非常强大的支持。

    代码

    import pandas
    pandas.read_csv('files/export.csv')
    

    结果

    【讨论】:

      猜你喜欢
      • 2016-11-15
      • 2011-11-25
      • 1970-01-01
      • 2018-02-15
      • 2011-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多