简体   繁体   中英

How To Solve KeyError: "None of [Index(['t1'], dtype='object')] are in the [columns]"

I'm trying to run code found on github for Hyperparameter Optimization and grid search. So, content of my csv file is as:

csv 内容:“treshold1.csv

So, my code is:

import pandas as pd
import svm

from random import randint
from sklearn import svm

#read data
dataframe=pd.read_csv("treshold1.csv")


X = dataframe[['t1']]
y = dataframe[['t2']]
best_score = 0  
best_params = {'C': None, 'gamma': None}

#for a preset number of iterations
for i in range(10):
    #try random values for each hyperparameter
    svc = svm.SVC(C=randint(0, 9), gamma=randint(0, 3))
    svc.fit(X, y)
    score = svc.score(Xval, yval)

    if score > best_score:
        best_score = score
        best_params['C'] = C
        best_params['gamma'] = gamma

best_score, best_params 

After run, i am getting this error:

 Traceback (most recent call last):
  File "g:/Maksa/Programiranje/Python/SI/image_quality_assessment-master/common/s.py", line 11, in <module>
    X = dataframe[['t1']]
  File "C:\Users\ftnkm\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\frame.py", line 3001, in __getitem__
    indexer = self.loc._convert_to_indexer(key, axis=1, raise_missing=True)
  File "C:\Users\ftnkm\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\indexing.py", line 1285, in _convert_to_indexer
    return self._get_listlike_indexer(obj, axis, **kwargs)[1]
  File "C:\Users\ftnkm\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\indexing.py", line 1092, in _get_listlike_indexer
    keyarr, indexer, o._get_axis_number(axis), raise_missing=raise_missing
  File "C:\Users\ftnkm\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\indexing.py", line 1177, in _validate_read_indexer
    key=key, axis=self.obj._get_axis_name(axis)
KeyError: "None of [Index(['t1'], dtype='object')] are in the [columns]"

I believe you just need to precise the column separator and decimal separator to the read_csv function. Note that it expects "," and "." by default. Try with: dataframe=pd.read_csv("treshold1.csv", sep=";", decimal=",")

Your code actually can run if your input file is indeed comma delimited.

However since you are getting a KeyError , it is likely that your input file treshold1.csv is not comma delimited.

Guessing from your screenshot of your 'csv' file content, I think your input file is probably tab delimited. Fix it and it should fix the KeyError .

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