csv 文件导入带有引号/作为字符串的数字列

csv file importing numeric columns with quotes/ as strings

我在处理一些同时包含数字和非数字列的 csv 文件时遇到了这个问题。

据我所知,

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

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

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

- 标记化数据时出错。 C 错误:第 129 行需要 1 个字段,但看到了 2

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

如何让 Python 理解或 strip/change 这种行为,以便导入数字列已经正常?

我尝试了不同的方法,例如 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 行中看到的那样,您看到带有两个“.”的数字。和“,”作为小数

如果您应用转换器函数,则可以将数据转换为正确的类型。 详情请见此处: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,
                          })