简体   繁体   中英

Value Error: Cannot convert string to float. CSV file opening with Pandas

I am trying to open a CSV dataset for decision tree learning. When I run the code it turns out with a value error. I think the problem is with the commas, but I don't know how to handle it.

import pandas as pd
from sklearn.tree import DecisionTreeClassifier 
from sklearn.model_selection import train_test_split 
from sklearn import metrics 

col_names = ['pregnant', 'glucose', 'bp', 'skin', 'insulin', 'bmi', 'pedigree', 'age', 'label']

pima = pd.read_csv(r'D:\MachinLearning\MyDataSets_Implementations\pima-indians-diabetes.csv', header=None, names=col_names)

pima.head()

some rows of dataset is like:

    Pregnancies,Glucose,BloodPressure,SkinThickness,Insulin,BMI,DiabetesPedigreeFunction,Age,Outcome
6,148,72,35,0,33.6,0.627,50,1 1,85,66,29,0,26.6,0.351,31,0
8,183,64,0,0,23.3,0.672,32,1 1,89,66,23,94,28.1,0.167,21,0
0,137,40,35,168,43.1,2.288,33,1 5,116,74,0,0,25.6,0.201,30,0

I don't get an error at all. It could help, to explicit define a separator in pd.csv_read(... sep=",") . You should also add (..., skiprows=1) in that function, to not read the fileheader as first datarow.

import pandas as pd
col_names = ['pregnant', 'glucose', 'bp', 'skin', 'insulin', 'bmi', 'pedigree', 'age', 'label']

csv_path = r'D:\MachinLearning\MyDataSets_Implementations\pima-indians-diabetes.csv'
pima = pd.read_csv(csv_path, header=1, names=col_names, sep=",", skiprows=1)
print(pima.head())

Gives the output


pregnant  glucose  bp  ...  pedigree  age  label 
6 148 72 35 0   33.6 0.627 50      1 1       85  66  ...     0.351   31      0
8 183 64 0  0   23.3 0.672 32      1 1       89  66  ...     0.167   21      0
0 137 40 35 168 43.1 2.288 33      1 5      116  74  ...     0.201   30      0

[3 rows x 9 columns]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM