【问题标题】:csv file importing numeric columns with quotes/ as stringscsv文件导入带引号的数字列/作为字符串
【发布时间】:2022-01-01 15:33:13
【问题描述】:

我在一些 csv 文件中遇到了这个问题,其中我有数字列和非数字列。

据我所见,Read.csv 将所有内容都导入为字符串,因为数字被单引号括起来,并且数字列看起来像“149.0”或“149,0”。 在这种情况下,我想去掉该引用以便以后进行转换。

当我有像一百万这样的数字时,它们看起来像这样:1.000,000

所以系统知道他需要引用,否则它将是另一个字段(因为第二个逗号不是一个点),我收到这些消息:

-错误标记数据。 C 错误:第 129 行中应有 1 个字段,看到 2

-无法将字符串转换为浮点数:'1.103.700'

如何让 Python 理解或去除/更改此行为,以便可以正常导入数字列?

我尝试了不同的方法,例如 quoting=2 (NON NUMERIC) 、 astype(float)、pd.replace ..... 没有任何效果。

我不知道我是用错误的命令还是什么读取文件。

你能帮帮我吗?例如,存在此问题的一列是 ccaavacunas.iloc[:,[3]]

文件在这里:https://github.com/jpiedehierroa/files/blob/main/ccaa_vacunas.csv

代码是这个:

import seaborn as sns
import pandas as pd

ccaavacunas = pd.read_csv("https://github.com/jpiedehierroa/files/blob/main/ccaa_vacunas.csv",keep_default_na=True,delimiter=',',decimal='.',quoting=2)
ccaavacunas

正如您在第 217 行中看到的那样,您会看到带有两个“.”的数字。和“,”作为小数

【问题讨论】:

  • 还要观察屏幕截图中的“0,05”。当应用 astype(float) 它不会改变类型

标签: python-3.x pandas dataframe csv format


【解决方案1】:

如果您应用转换器功能,则可以将数据转换为正确的类型。 更多详情请看这里:https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html?highlight=read_csv

import pandas as pd


def converter_function(value_to_convert):
    # Replace "," with "." and assign to a new variable
    converted_value = value_to_convert.replace(",", ".")

    # Check if there is more than one occurrence of "."
    if converted_value.count(".") > 1:
        converted_value = converted_value.replace(".", "")

    # Convert to float type if value allows, if not return the original value
    converted_value = float(converted_value) if converted_value.replace('.', '', 1).isdigit() else value_to_convert

    return converted_value


ccaavacunas = pd.read_csv("ccaa_vacunas.csv", keep_default_na=True, delimiter=',', decimal='.', quoting=1,
                          converters={
                              'Dosis entregadas Pfizer': converter_function,
                              'Dosis entregadas Moderna': converter_function,
                              'Dosis entregadas AstraZeneca': converter_function,
                              'Dosis entregadas Janssen': converter_function,
                              'Dosis entregadas totales': converter_function,
                              'Dosis administradas': converter_function,
                              'Porcentaje de dosis administradas por 100 habitantes': converter_function,
                              'Porcentaje sobre entregadas': converter_function,
                              'Personas con pauta completa': converter_function,
                              'Porcentaje con pauta completa': converter_function,
                          })

【讨论】:

    猜你喜欢
    • 2014-02-08
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    相关资源
    最近更新 更多