![](/img/trans.png)
[英]ValueError: could not convert string to float: 'F' python
[英]“ValueError: could not convert string to float” in Python
在嘗試實現下面提到的代碼時,我得到“無法將字符串轉換為浮動”錯誤。 在代碼中,我基本上讀取CSV文件並嘗試將字符串值(所有值都是數字)轉換為float。
import csv
def loadCsv(filename):
lines = csv.reader(open(filename, "rt"))
dataset = list(lines)
for i in range(len(dataset)):
dataset[i] = [float(x) for x in dataset[i]]
return dataset
filename = 'Pima Diabetes.csv'
dataset = loadCsv(filename)
print('Loaded data file {0} with {1} rows').format(filename, len(dataset))
數據集的第一行包含基本上為“字符串”的要素名稱。 根據您的代碼,您將數據集中的每一行轉換為浮點數,其中還包括要素名稱。 你想要的是讓你的代碼從第二行讀取行。
在大多數情況下,使用csv和open是很難的。 你可以簡單地說
#pip install pandas
import pandas as pd
# read csv to a data frame
# sep is default to ','. You can change with sep='\t' for tab,
df = pd.read_csv('YOUR_CSV.csv')
# print the number of rows and columns
print(df.shape)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.