【问题标题】:Could not convert string to float (Pandas)无法将字符串转换为浮点数(熊猫)
【发布时间】:2020-05-26 15:36:31
【问题描述】:

我想从 .csv 文件中读取数据行,每当我运行我的代码时,它都会弹出这个错误。我不知道如何解决这个问题。我查了一些类似的帖子,但仍然无法解决。

这是我的代码:

def getThreshold(dataSet, Attributes, isNumeric):
    '''
        Calculates median threshold from train dataset
    '''
    thresholds = []
    for x in Attributes:
        indx = Attributes.index(x)
        numeric = isNumeric[indx]
        if numeric:
            listAtt = []
            for row in dataSet:
                listAtt.append(float(row[indx]))     
            # calculate median a numeric attribute column
            median = statistics.median(listAtt)
            thresholds.append(median)
    return thresholds

这是我的示例数据,(不带引号)

41,management,single,secondary,no,764,no,no,cellular,12,jun,230,2,-1,0,unknown,no
39,blue-collar,married,secondary,no,49,yes,no,cellular,14,may,566,1,370,2,failure,no
60,retired,married,primary,no,0,no,no,telephone,30,jul,130,3,-1,0,unknown,no
31,entrepreneur,single,tertiary,no,247,yes,yes,unknown,2,jun,273,1,-1,0,unknown,no

发现问题的第一列是年龄,被标识为字符串。是csv文件的问题还是代码的问题?

【问题讨论】:

  • 请将此减少并增强为预期的MRE

标签: python csv


【解决方案1】:

如果不可能,将变量转换为浮点数会引发 ValueError。更改了您的代码以进行检查。

def getThreshold(dataSet, Attributes, isNumeric):
    '''
        Calculates median threshold from train dataset
    '''
    thresholds = []
    for x in Attributes:
        indx = Attributes.index(x)
        numeric = isNumeric[indx]
        if numeric:
            listAtt = []
            for row in dataSet:
                value = row[indx]
                # Try to convert value to float, if it fails then it keeps the original type
                try:
                    value = float(value)
                except ValueError:
                    pass
                listAtt.append(value)
            # calculate median a numeric attribute column
            median = statistics.median(listAtt)
            thresholds.append(median)
    return thresholds

附带说明: 所有变量都应以小写字母开头。 只有类定义应该以大写开头。

【讨论】:

  • 我发现了错误。数据的第一列被标识为字符串。我可以知道如何解决吗?是代码的问题还是 .csv 文件的问题?
  • 如果您使用的是 pandas 数据框,那么您可以轻松转换类型,请参阅stackoverflow.com/questions/16729483/…。您还应该尝试不迭代数据框,请参阅此处stackoverflow.com/questions/16476924/…。基本上我建议尝试重写它,这样你就可以直接从读取 csv 文件中获取数据帧,然后使用 panda 的内置方法来获取中位数等。
  • 我现在唯一遇到的问题是第一列被识别为字符串而不是数字,其他列中的数字没有问题。我尝试在 excel 中更改列的格式,但所做的更改无法保存。我可以知道如何解决这个问题吗?
  • 您是否尝试过pd.Series.astype(float)pd.to_numeric,正如我发布的链接所解释的那样?
  • 我试过了,但还是一样。我得到 \ufeff43 而不是数字 43
猜你喜欢
  • 1970-01-01
  • 2020-11-05
  • 1970-01-01
  • 2017-10-25
  • 1970-01-01
  • 2020-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多