KeyError при использовании Pandas для доступа к CSV-файлам - PullRequest
0 голосов
/ 02 октября 2019

Я успешно создал CSV-файл, используя панд. Я получаю следующую ошибку:

Traceback (последний вызов был последним): файл "C: \ Users \ Manoj Kumar \ PycharmProjects \ trex \ venv \ lib \ site-packages \ pandas \ core \ indexes \ base. py ", строка 3078, в get_loc возвращает self._engine.get_loc (key) файл" pandas_libs \ index.pyx ", строка 140, в файле pandas._libs.index.IndexEngine.get_loc" pandas_libs \ index.pyx ", строка 162, в файле pandas._libs.index.IndexEngine.get_loc "pandas_libs \ hashtable_class_helper.pxi", строка 1492, в файле pandas._libs.hashtable.PyObjectHashTable.get_item "pandas_libs \ hashtable_pi. hashtable.PyObjectHashTable.get_item KeyError: 'Id'

Во время обработки вышеупомянутого исключения произошло другое исключение:

Трассировка (последний вызов был последним): файл "C: \ Users \ Manoj Kumar\ AppData \ Local \ Programs \ Python \ Python37 \ lib \ tkinter__init __. Py ", строка 1702, в call return self.func (* args) Файл" C: / Users / Manoj Kumar / PycharmProjects / trex "/ Менеджмент посещаемости на основе распознавания лиц -Скопируйте / train.py ", строка 206, в TrackImages aa = df.iloc [df ['Id'] == Id] ['Name']. Файл значений" C: \ Users \ Manoj Kumar \ PycharmProjects \ trex \ venv\ lib \ site-packages \ pandas \ core \ frame.py ", строка 2688, в getitem return self._getitem_column (key) Файл" C: \ Users \ Manoj Kumar \ PycharmProjects \ trex \ venv \ "lib \ site-packages \ pandas \ core \ frame.py ", строка 2695, в _getitem_column возвращает self._get_item_cache (ключ) Файл" C: \ Users \ Manoj Kumar \ PycharmProjects \ trex \ venv \ lib \ site-packages \ pandas "\ core \ generic.py ", строка 2489, в значениях _get_item_cache = self._data.get (item) Файл" C: \ Users \ Manoj Kumar \ PycharmProjects \ trex \ venv \ lib \ site-packages \ pandas \ core \ internals ".py ", строка 4115, в get loc = self.items.get_loc (item) Файл" C: \ Users \ Manoj Kumar \ PycharmProjects \ trex \ venv \ lib \ site-packages \ pandas \ core \ indexes \ base.py", строка 3080, в get_loc возвращает self._engine.get_loc (self._maybe_cast_indexer (key)) файл" pandas_libs \ index.pyx ", строка 140, в файле pandas._libs.index.IndexEngine.get_loc" pandas_libs \ index.pyx "»,строка 162, в файле pandas._libs.index.IndexEngine.get_loc "pandas_libs \ hashtable_class_helper.pxi", строка 1492, в файле pandas._libs.hashtable.PyObjectHashTable.get_item "pandas_libs \ pashas.lix_ line_px. _libs.hashtable.PyObjectHashTable.get_item KeyError: 'Id'

при попытке доступа к файлу csv из кода. Код:

    recognizer = cv2.face.EigenFaceRecognizer_create()  # cv2.createLBPHFaceRecognizer()
    recognizer.read("TrainingImageLabel\Trainner.yml")
    harcascadePath = "haarcascade_frontalface_default.xml"
    faceCascade = cv2.CascadeClassifier(harcascadePath);
    df = pd.read_csv("StudentDetails\StudentDetails.csv")
    cam = cv2.VideoCapture(0)
    font = cv2.FONT_HERSHEY_SIMPLEX
    col_names = ['Id', 'Name', 'Date', 'Time']
    attendance = pd.DataFrame(columns=col_names)
    while True:
        ret, im = cam.read()
        gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
        faces = faceCascade.detectMultiScale(gray, 1.2, 5)
        if np.all(np.array(np.array(faces).shape)) and faces is not None:
            for (x, y, w, h) in faces:
                cv2.rectangle(im, (x, y), (x + w, y + h), (225, 0, 0), 2)
                gray = gray[y:y + h, x:x + w]
                gray = cv2.resize(gray, (100, 100))
                Id, conf = recognizer.predict(gray)
                print(Id, conf)
                if (conf < 2000):
                    ts = time.time()
                    date = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d')
                    timeStamp = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')
                    aa = df.loc[df['Id'] == Id]['Name'].values
                    tt = str(Id) + "-" + aa
                    attendance.loc[len(attendance)] = [Id, aa, date, timeStamp]
                else:
                    Id = 'Unknown'
                    tt = str(Id)
                if (conf > 2000):
                    noOfFile = len(os.listdir("ImagesUnknown")) + 1
                    cv2.imwrite("ImagesUnknown\Image" + str(noOfFile) + ".jpg", im[y:y + h, x:x + w])
                cv2.putText(im, str(tt), (x, y + h), font, 1, (255, 255, 255), 2)
        attendance = attendance.drop_duplicates(subset=['Id'], keep='first')
        cv2.imshow('im', im)
        if (cv2.waitKey(1) == ord('q')):
            break
    ts = time.time()
    date = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d')
    timeStamp = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')
    Hour, Minute, Second = timeStamp.split(":")
    fileName = "Attendance\Attendance_" + date + "_" + Hour + "-" + Minute + "-" + Second + ".csv"
    attendance.to_csv(fileName, index=False)
    cam.release()
    cv2.destroyAllWindows()
    # print(attendance)
    res = attendance
    message2.configure(text=res)```

The objective of the code is to recognize faces.

1 Ответ

0 голосов
/ 02 октября 2019

Похоже, что вы потерпели неудачу в этой строке:

aa = df.loc[df['Id'] == Id]['Name'].values

, и это, вероятно, потому, что CSV не содержит столбец с именем "Id".

Пожалуйста, проверьте это! (

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...