KeyError python
deristix Messages postés 55 Date d'inscription Statut Membre Dernière intervention -
Bonsoir
J'ai déjà envoyé un message sur le forum par rapport à mon programme, mais là j'ai un autre problème.
Quand je veux faire la recherche de figures géométriques (avec la fonction search_figures) dans laquelle j'ajoute la variable (df) dans le programme ci-dessous j'ai un message d'erreur qui est celui-ci:
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "C:\Users\LOIC\Desktop\polygone3.py", line 54, in polygone_find
xA=A[tri[0]+1]
File "C:\EduPython\App\lib\site-packages\pandas\core\frame.py", line 2800, in __getitem__
indexer = self.columns.get_loc(key)
File "C:\EduPython\App\lib\site-packages\pandas\core\indexes\base.py", line 2648, in get_loc
return self._engine.get_loc(self._maybe_cast_indexer(key))
File "pandas\_libs\index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\hashtable_class_helper.pxi", line 1619, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas\_libs\hashtable_class_helper.pxi", line 1627, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 1
#ce programme sert à reconnaitre des figures géométriques particulières dans un nuage de points import pandas as pd df = pd.read_csv("monFichier_test.csv") print (df) '''cette fonction permet de definir un carré''' def test_carre(xA,yA,xB,yB,xC,yC,xD,yD): a=((xB-xA)**2+(yB-yA)**2) b=((xC-xB)**2+(yC-yB)**2) c=((xD-xC)**2+(yD-yC)**2) d=((xA-xD)**2+(yA-yD)**2) if a==b==c==d and ((xC-xB)*(xD-xC)+(yC-yB)*(yD-yC))==0 and ((xB-xA)*(xA-xD)+(yB-yA)*(yA-yD))==0: return True else: return False '''cette fonction permet de definir un rectangle ''' def test_rectangle(xA,yA,xB,yB,xC,yC,xD,yD): a=((xB-xA)**2+(yB-yA)**2) b=((xC-xB)**2+(yC-yB)**2) c=((xD-xC)**2+(yD-yC)**2) d=((xA-xD)**2+(yA-yD)**2) if a==c and b==d and ((xC-xB)*(xD-xC)+(yC-yB)*(yD-yC))==0 and ((xB-xA)*(xA-xD)+(yB-yA)*(yA-yD))==0: return True else: return False '''cette fonction permet de definir un triangle rectangle''' def test_trianglerectangle(xA,yA,xB,yB,xC,yC): a=((xB-xA)**2+(yB-yA)**2) b=((xC-xB)**2+(yC-yB)**2) c=((xA-xC)**2+(yA-yC)**2) if b*b==a*a+c*c and ((xB-xA)*(xC-xA)+(yB-yA)*(yC-yA))==0: return True else: return False from itertools import* def search_figures(A): n=len(A) B=list(range(0,n,2)) trianglerectangle=[] carre=[] rectangle=[] RESULTAT={} '''je fais la recherche de triangles rectangles''' C=list(combinations(B,4)) for tri in C: xA=A[tri[0]] yA=A[tri[0]+1] xB=A[tri[1]] yB=A[tri[1]+1] xC=A[tri[2]] yC=A[tri[2]+1] print("av",xA,yA,xB,yB,xC,yC) if test_trianglerectangle(xA,yA,xB,yB,xC,yC): test_trianglerectangle.append((tri[0],tri[1],tri[2])) RESULTAT.update({"trianglerectangle":trianglerectangle}) '''je fais la recherche de carré''' C=list(combinations(B,4)) for tri in C: xA=A[tri[0]] yA=A[tri[0]+1] xB=A[tri[1]] yB=A[tri[1]+1] xC=A[tri[2]] yC=A[tri[2]+1] xD=A[tri[3]] yD=A[tri[3]+1] print("av",xA,yA,xB,yB,xC,yC,xD,yD) if test_carre(xA,yA,xB,yB,xC,yC,xD,yD): carre.append((tri[0],tri[1],tri[2],tri[3])) RESULTAT.update({"carre":carre}) '''je fais la recherche de rectangle''' C=list(combinations(B,4)) for tri in C: xA=A[tri[0]] yA=A[tri[0]+1] xB=A[tri[1]] yB=A[tri[1]+1] xC=A[tri[2]] yC=A[tri[2]+1] xD=A[tri[3]] yD=A[tri[3]+1] print("av",xA,yA,xB,yB,xC,yC,xD,yD) if test_rectangle(xA,yA,xB,yB,xC,yC): rectangle.append((tri[0],tri[1],tri[2],tri[3])) RESULTAT.update({"rectangle":rectangle}) '''la structure retournée est le dictionnaire RESULTAT''' return(RESULTAT) import matplotlib.pyplot as plt x = [47.17788031846174 ,9.155162513788252 ,87.31106451765086 ,90.18098777410545 ,85.73425568394163 ,69.21660923542944 ,87.42386051005897 ,35.27685634185226 ,83.01845522622216 ,45.32537448340496 ,51.322646552859695 ,69.9527028251635 ,3.08569815272679 ,66.30463831578771 ,62.41033400206221 ,80.05712601988002 ,10 ,10 ,70 ,10 ,30 ,90 ,70 ,30 ,70 ,89.11423668645706 ,92.58342391495769 ,44.22604145548783 ,95.42720095700402 ,21.435826737054732 ,19.37910846507328 ,48.943206051376606 ,97.68362835412275 ,72.59631895251266 ,63.809973321904366 ,31.42076659631765 ,83.88946390215908 ,62.116866264263216 ,16.46862820087156] y = [7.856866949374341 ,32.60533028920386 ,7.9593054773530625 ,97.74037355348855 ,11.752247867249043 ,19.38838353746982 ,23.839873731365046 ,13.752179944089926 ,31.00629476536042 ,9.428326440424428 ,59.5011025964827 ,73.64015636941087 ,55.46780269542562 ,28.89261106782417 ,41.65910883295687 ,2.6141574612408958 ,10 ,70 ,10 ,10 ,50 ,50 ,10 ,10 ,50 ,73.20222328424518 ,16.76132763110746 ,1.0615177467627968 ,17.271594103822896 ,14.310405723515663 ,57.269925634522856 ,82.43371784928712 ,48.3488192958625 ,56.325210197081134 ,12.977441456959616 ,59.135914263212065 ,23.574727012142937 ,45.42966847449507 ,63.35434423882829] plt.scatter(x,y) plt.title('poco y para avec Matplotlib') plt.xlabel('x') plt.ylabel('y') plt.savefig('ScatterPlot_01.png') plt.plot(x,y) plt.show()
pourriez vous m'aider svp ?
4 réponses
bonjour,
Peux-tu partager le programme que tu exécutes, ainsi que le fichier lu par le programme?
bonjour,
j'essaie d'envoyer le fichier excel mais je n'y arrive pas comment dois-je l'envoyer ?
le programme exécuté est le code de mon message précédent.
ahh oui le "polygone_find" je l'avais remplace par la fonction "search_figures".
voici le lien vers mon fichier csv:
https://onedrive.live.com/redir?resid=27F7334224EF46BE!153&authkey=!AEV48GOmO_9kkxQ&ithint=file%2cxlsx&e=ThvsLF
Salut.
Plusieurs problèmes, si ton csv a autre chose qu'une virgule comme séparateur, alors il faut le préciser, et ensuite convertir en liste.
import pandas as pd df = pd.read_csv("monFichier_test.csv", sep='\t') data = df.values.tolist()
Mais inutile de se servir de pandas pour lire un simple fichier csv, mieux vaut utiliser le module csv.
import csv with open("monFichier_test.csv") as f: reader = csv.DictReader(f, delimiter='\t') data = tuple(tuple(float(v) for v in row.values()) for row in reader)
itertools.combination retourne donc des indices de tes coordonnées. Tu ne dois pas incrémenter ces indices, car évidemment si on se trouve au dernier indice, il y aura une erreur comme celle que tu obtiens puisqu'on tentera d'accéder à un indice inexistant, de plus ce n'est pas ce qu'il faut faire, juste utiliser les indices de ta liste d'indices.
# .... '''je fais la recherche de triangles rectangles''' C = list(combinations(B, 3)) # 3 et non 4 for tri in C: xA = A[tri[0]][0] yA = A[tri[0]][1] xB = A[tri[1]][0] yB = A[tri[1]][1] xC = A[tri[2]][0] yC = A[tri[2]][1] if test_trianglerectangle(xA,yA,xB,yB,xC,yC): trianglerectangle.append((tri[0],tri[1],tri[2])) # trianglerectangle ! RESULTAT.update({"trianglerectangle": trianglerectangle}) # ...
Faire de même avec les autres boucles.