使用熊猫访问csv文件时出现KeyError

时间:2019-10-02 07:13:20

标签: python python-3.x pandas csv dataframe

我已经使用熊猫成功创建了一个csv文件。我收到以下错误:

回溯(最近通话最近):   在get_loc中的文件“ C:\ Users \ Manoj Kumar \ PycharmProjects \ trex \ venv \ lib \ site-packages \ pandas \ core \ indexes \ base.py”,行3078     返回self._engine.get_loc(key)   在pandas._libs.index.IndexEngine.get_loc中的文件“ pandas_libs \ index.pyx”,第140行   在pandas._libs.index.IndexEngine.get_loc中的文件“ pandas_libs \ index.pyx”,第162行   在pandas._libs.hashtable.PyObjectHashTable.get_item中的文件“ pandas_libs \ hashtable_class_helper.pxi”,行1492   在pandas._libs.hashtable.PyObjectHashTable.get_item中的文件“ pandas_libs \ hashtable_class_helper.pxi”,行1500 KeyError:“ Id”

在处理上述异常期间,发生了另一个异常:

回溯(最近通话最近):   在调用中的文件“ C:\ Users \ Manoj Kumar \ AppData \ Local \ Programs \ Python \ Python37 \ lib \ tkinter__init __。py”,第1702行     返回self.func(* args)   在TrackImages中的文件“ C:/ Users / Manoj Kumar / PycharmProjects / trex /基于面部识别的出勤管理-Copy / train.py”,行206     aa = df.iloc [df ['Id'] == Id] ['Name']。values    getitem 中的文件“ C:\ Users \ Manoj Kumar \ PycharmProjects \ trex \ venv \ lib \ site-packages \ pandas \ core \ frame.py”,行2688     返回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(key)   文件“ C:\ Users \ Manoj Kumar \ PycharmProjects \ trex \ venv \ lib \ site-packages \ pandas \ core \ generic.py”,行2489,在_get_item_cache中     值= self._data.get(项目)   在获得的文件“ C:\ Users \ Manoj Kumar \ PycharmProjects \ trex \ venv \ lib \ site-packages \ pandas \ core \ internals.py”中,行4115     loc = self.items.get_loc(item)   get_loc中的文件“ C:\ Users \ Manoj Kumar \ PycharmProjects \ trex \ venv \ lib \ site-packages \ pandas \ core \ indexes \ base.py”,行3080     返回self._engine.get_loc(self._maybe_cast_indexer(key))   在pandas._libs.index.IndexEngine.get_loc中的文件“ pandas_libs \ index.pyx”,第140行   在pandas._libs.index.IndexEngine.get_loc中的文件“ pandas_libs \ index.pyx”,第162行   在pandas._libs.hashtable.PyObjectHashTable.get_item中的文件“ pandas_libs \ hashtable_class_helper.pxi”,行1492   在pandas._libs.hashtable.PyObjectHashTable.get_item中的文件“ pandas_libs \ hashtable_class_helper.pxi”,行1500 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 :(得分:0)

似乎在此行失败:

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

这可能是因为csv不包含名为'Id'的列。

请检查一下! (: