我在一些 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]]
該檔案在這里:
uj5u.com熱心網友回復:
如果您應用轉換器功能,則可以將資料轉換為正確的型別。有關更多詳細資訊,請參見此處: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,
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/400252.html
