2017-03-18 4 views
0

목표는 파일을 반복하고 공격적인 리바운드와 관련하여 상위 5 개 팀과 플레이어를 찾는 것입니다. 파일에 여러 팀이 여러 게임을 포함하고 있습니다. 예를 들어, Grizzlies vs Bears가 플레이하고 그리즐리스 출신 선수가 3 리바운드를 기록한 다음 Grizzlies vs the Sharks에서 몇 백 라인을 더할 수 있으며, 5 리바운드를 얻을 수도 있습니다.루핑으로 인한 이상한 Python 오류

목표는 전체 파일을 반복하는 루프 내에 루프를 넣는 것입니다 (예 : '리바운드 끄기 (1)', '리바운드 끄기 (2)', '리바운드 끄기 . 나는 한 경기 당 가장 리바운드가 10이라는 것을 알 수있었습니다. 정말 못생긴 것을하고 10 개의 if/else 문 1-10을 넣기보다는 변수 (k) 1-10을 더해서 (코드를 잘못 작성했다는 것을 알기 위해 시간을 내고 싶다.) 오늘 밤 처음으로 앉아서 파이썬을 처음 보았고 그것을 완벽하게 기능하는 코드를 얻을 때 가능한 최선으로 수정하십시오. 어쩌면 그렇게하는 것이 나쁜 방법이지만, 그렇게 할 것입니다.) 불행히도, 나는이 코드 밑에 붙여 넣은이 이상한 오류를 얻습니다.

import pandas as pd 
import collections as c 

fileRead = pd.read_csv('Sample.csv') 

eventDescript = fileRead.event_desc.apply(str) 
team = fileRead.team_name.apply(str) 
player = fileRead.player_name.apply(str) 
topTeams = [] 
topPlayers = [] 
i = 0 

while (i != len(eventDescript)): 
    # print eventDescript.where(eventDescript == 'Off Rebound (1)').dropna() 
    for k in range(1,11): 
     if eventDescript[i] == 'Off Rebound (' + str(k) + ')' and player[i] != 'nan': 
      topTeams.append(team[i]) 
      topPlayers.append(player[i]) 
      i = i + 1 
     else: 
      i = i + 1 
    i = i + 1 

print c.Counter(topTeams).most_common(5) 
print c.Counter(topPlayers).most_common(5) 

runfile('/Users/air13/Downloads/untitled2.py', wdir='/Users/air13/Downloads') 

오류 : 역 추적 (마지막으로 가장 최근 통화) :

File "<ipython-input-239-f1cd8a80a240>", line 1, in <module> 
    runfile('/Users/air13/Downloads/untitled2.py', wdir='/Users/air13/Downloads') 
    File "/Users/air13/anaconda/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py", line 866, in runfile 
    execfile(filename, namespace) 
    File "/Users/air13/anaconda/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py", line 94, in execfile 
    builtins.execfile(filename, *where) 
    File "/Users/air13/Downloads/untitled2.py", line 24, in <module> 
    if eventDescript[i] == 'Off Rebound (' + str(k) + ')' and player[i] != 'nan': 
    File "/Users/air13/anaconda/lib/python2.7/site-packages/pandas/core/series.py", line 603, in __getitem__ 
    result = self.index.get_value(self, key) 
    File "/Users/air13/anaconda/lib/python2.7/site-packages/pandas/indexes/base.py", line 2169, in get_value 
    tz=getattr(series.dtype, 'tz', None)) 
    File "pandas/index.pyx", line 98, in pandas.index.IndexEngine.get_value (pandas/index.c:3557) 
    File "pandas/index.pyx", line 106, in pandas.index.IndexEngine.get_value (pandas/index.c:3240) 
    File "pandas/index.pyx", line 154, in pandas.index.IndexEngine.get_loc (pandas/index.c:4279) 
    File "pandas/src/hashtable_class_helper.pxi", line 404, in pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:8564) 
    File "pandas/src/hashtable_class_helper.pxi", line 410, in pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:8508) 
KeyError: 128651 

답변

1

이 오류가 라인에서 발생했습니다 if eventDescript[i] == 'Off Rebound (' + str(k) + ')' and player[i] != 'nan': 그것은 키 오류, 그래서 키 에 대한 값이없는 내가eventDescript 또는 플레이어 사전. 당신은! = 대신 while 루프에서 <을 사용하고 내가 세 번 증가하기 때문에 것을 내가이 사전의 길이보다 큰되었다 있도록 이있다.

import pandas as pd 
import collections as c 

fileRead = pd.read_csv('Sample.csv') 

eventDescript = fileRead.event_desc.apply(str) 
team = fileRead.team_name.apply(str) 
player = fileRead.player_name.apply(str) 
topTeams = [] 
topPlayers = [] 

for i in range(len(eventDescript)): 
    # print eventDescript.where(eventDescript == 'Off Rebound (1)').dropna() 
    if player[i] != 'nan': 
     k = int(eventDescript[i].replace('Off Rebound (', '').replace(')', '')) 
     if 1 <= k <= 10: 
      topTeams.append(team[i]) 
      topPlayers.append(player[i]) 

print(c.Counter(topTeams).most_common(5)) 
print(c.Counter(topPlayers).most_common(5)) 
  1. 난 당신이 항상을 위해 - 루프 가능하면 사용하는 것이 좋습니다, 그래서 오류의 이러한 종류도 일어날 수 없습니다 : 여기

    내가 그것을했을 방법이다.

  2. 두 번째 루프가 필요하지 않습니다. 대신 내가의
  3. 은 = I + 1은 내가 + = 1
+0

내가 도움을 주셔서 감사합니다, seenorth 사용할 수도! – Tyler