我们的目标是遍历一个文件,找出进攻篮板排名前5的球队和球员。文件中包含多个团队玩的多个游戏。例如,灰熊对熊的比赛,有人可能从灰熊得到3个篮板,然后几百线下灰熊对鲨鱼,有人可能得到5个篮板。它的格式如下:'反跳(1)''反跳(2)''反跳(3)'等
目标是在循环中放置一个循环,循环遍历整个文件。我发现每场比赛最多的篮板是10个。我想添加一些变量(k)1-10,使它不那么草率(我想花时间说我意识到代码不是很好)。今晚我第一次坐下来看它,我对Python还比较陌生,当我得到一个完整的函数代码时,我会尽可能地修改它。。也许这样做不好,但我会这么做)。不幸的是,我得到了这个非常奇怪的错误,我粘贴在我的代码下面。你知道吗
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
行中出现错误:
if eventDescript[i] == 'Off Rebound (' + str(k) + ')' and player[i] != 'nan':
这是一个键错误,因此在eventDescript或player字典中没有键i的值。 这是因为你使用了!=而不是while循环中的<;,并将i增加三倍,使i大于词典的长度。你知道吗我会这样做:
相关问题 更多 >
编程相关推荐