Python键错误
我是Python的新手,刚刚开始学习。我正在根据以前的成绩做一项运动预习。我有两个csv文件,一个是今年的所有比赛,另一个是排名(锦标赛的最终结果和排名+唯一的对象-我的意思是我只有14行)。问题在于排名csv如下所示:Python键错误,python,pandas,dataframe,csv,Python,Pandas,Dataframe,Csv,我是Python的新手,刚刚开始学习。我正在根据以前的成绩做一项运动预习。我有两个csv文件,一个是今年的所有比赛,另一个是排名(锦标赛的最终结果和排名+唯一的对象-我的意思是我只有14行)。问题在于排名csv如下所示: Squad,Rk,MP,W,D,L,GF,GA,GD,Pts,Pts/G,MP,W,D,L,GF,GA,GD,Pts,Pts/G CFR Cluj,1,18,13,5,0,24,5,19,44,2.44,18,10,5,3,30,14,16,35,1.94 我有一段代码,它
Squad,Rk,MP,W,D,L,GF,GA,GD,Pts,Pts/G,MP,W,D,L,GF,GA,GD,Pts,Pts/G
CFR Cluj,1,18,13,5,0,24,5,19,44,2.44,18,10,5,3,30,14,16,35,1.94
我有一段代码,它为我从csv中采样的第一行引发了关键错误
def home_team_ranks_higher(row):
home_team = row["Home"]
visitor_team = row["Away"]
home_rank = standings.loc[home_team]["Rk"]
visitor_rank = standings.loc[visitor_team]["Rk"]
return home_rank < visitor_rank
dataset["HomeTeamRanksHigher"] = dataset.apply(home_team_ranks_higher, axis = 1)
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-112-d3a62e1e7d32> in <module>
6 return home_rank < visitor_rank
7
----> 8 dataset["HomeTeamRanksHigher"] = dataset.apply(home_team_ranks_higher, axis = 1)
9
10 #dataset["HomeTeamRanksHigher"] = 0
~\anaconda3\lib\site-packages\pandas\core\frame.py in apply(self, func, axis, raw, result_type, args, **kwds)
7546 kwds=kwds,
7547 )
-> 7548 return op.get_result()
7549
7550 def applymap(self, func) -> "DataFrame":
~\anaconda3\lib\site-packages\pandas\core\apply.py in get_result(self)
178 return self.apply_raw()
179
--> 180 return self.apply_standard()
181
182 def apply_empty_result(self):
~\anaconda3\lib\site-packages\pandas\core\apply.py in apply_standard(self)
269
270 def apply_standard(self):
--> 271 results, res_index = self.apply_series_generator()
272
273 # wrap results
~\anaconda3\lib\site-packages\pandas\core\apply.py in apply_series_generator(self)
298 for i, v in enumerate(series_gen):
299 # ignore SettingWithCopy here in case the user mutates
--> 300 results[i] = self.f(v)
301 if isinstance(results[i], ABCSeries):
302 # If we have a view on v, we need to make a copy because
<ipython-input-112-d3a62e1e7d32> in home_team_ranks_higher(row)
2 home_team = row["Home"]
3 visitor_team = row["Away"]
----> 4 home_rank = standings.loc[home_team]["Rk"]
5 visitor_rank = standings.loc[visitor_team]["Rk"]
6 return home_rank < visitor_rank
~\anaconda3\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key)
877
878 maybe_callable = com.apply_if_callable(key, self.obj)
--> 879 return self._getitem_axis(maybe_callable, axis=axis)
880
881 def _is_scalar_access(self, key: Tuple):
~\anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_axis(self, key, axis)
1108 # fall thru to straight lookup
1109 self._validate_key(key, axis)
-> 1110 return self._get_label(key, axis=axis)
1111
1112 def _get_slice_axis(self, slice_obj: slice, axis: int):
~\anaconda3\lib\site-packages\pandas\core\indexing.py in _get_label(self, label, axis)
1057 def _get_label(self, label, axis: int):
1058 # GH#5667 this will fail if the label is not present in the axis.
-> 1059 return self.obj.xs(label, axis=axis)
1060
1061 def _handle_lowerdim_multi_index_axis0(self, tup: Tuple):
~\anaconda3\lib\site-packages\pandas\core\generic.py in xs(self, key, axis, level, drop_level)
3489 loc, new_index = self.index.get_loc_level(key, drop_level=drop_level)
3490 else:
-> 3491 loc = self.index.get_loc(key)
3492
3493 if isinstance(loc, np.ndarray):
~\anaconda3\lib\site-packages\pandas\core\indexes\range.py in get_loc(self, key, method, tolerance)
356 except ValueError as err:
357 raise KeyError(key) from err
--> 358 raise KeyError(key)
359 return super().get_loc(key, method=method, tolerance=tolerance)
360
KeyError: 'CFR Cluj'
def home\u团队排名更高(世界其他地区):
主场团队=第[“主场”]
访客团队=行[“离开”]
主场排名=排名。loc[主场队][“Rk”]
访客排名=排名。loc[访客团队][“Rk”]
返乡等级<访客等级
dataset[“HomeTeamRanksHigher”]=dataset.apply(home\u team\u排名更高,axis=1)
---------------------------------------------------------------------------
KeyError回溯(最近一次呼叫最后一次)
在里面
6返乡等级<访客等级
7.
---->8数据集[“HomeTeamRanksHigher”]=数据集。应用(home\u team\u排名更高,axis=1)
9
10#数据集[“HomeTeamRanksHigher”]=0
应用中的~\anaconda3\lib\site packages\pandas\core\frame.py(self、func、axis、raw、result\u type、args、**kwds)
7546科威特第纳尔=科威特第纳尔,
7547 )
->7548返回操作获取结果()
7549
7550 def applymap(self,func)->“数据帧”:
获取结果(self)中的~\anaconda3\lib\site packages\pandas\core\apply.py
178返回自我。应用_原始()
179
-->180返回自我应用标准()
181
182 def应用\空\结果(自身):
应用标准中的~\anaconda3\lib\site packages\pandas\core\apply.py(self)
269
270 def应用_标准(自):
-->271结果,res_index=self.apply_系列_生成器()
272
273#总结结果
应用系列生成器中的~\anaconda3\lib\site packages\pandas\core\apply.py(自)
298对于枚举中的i、v(系列):
299#在此处使用copy忽略设置,以防用户发生变异
-->300结果[i]=自f(v)
301如果存在(结果[i],ABC系列):
302#如果我们对v有看法,我们需要复制一份,因为
主场球队排名更高(世界其他地区)
2主场团队=第[“主场”]
3访客团队=行[“离开”]
---->4主队排名=排名。loc[主队][“Rk”]
5访客排名=排名。loc[访客团队][“Rk”]
6返乡等级<访客等级
~\anaconda3\lib\site packages\pandas\core\index.py in\uuuuu getitem\uuuuuu(self,key)
877
878 maybe_callable=com.apply_if_callable(key,self.obj)
-->879返回自我。获取项目轴(可能可调用,轴=轴)
880
881定义是标量访问(self,key:Tuple):
轴中的~\anaconda3\lib\site packages\pandas\core\index.py(self、key、axis)
1108#通过直线查找
1109自我验证键(键,轴)
->1110返回自我。获取标签(键,轴=轴)
1111
1112定义获取切片轴(self,切片对象:切片,轴:int):
~\anaconda3\lib\site packages\pandas\core\index.py in\u get\u标签(self、label、axis)
1057 def_get_标签(自身、标签、轴:int):
1058#GH#5667如果轴上没有标签,则此操作将失败。
->1059返回self.obj.xs(标签,轴=轴)
1060
1061 def _handle _lowerdim _multi _index _axis0(self,tup:Tuple):
xs中的~\anaconda3\lib\site packages\pandas\core\generic.py(self、key、axis、level、drop_level)
3489 loc,新索引=自索引。获取loc级别(键,删除级别=删除级别)
3490其他:
->3491 loc=自索引获取位置(键)
3492
3493如果存在(位置,np.N阵列):
get\u loc中的~\anaconda3\lib\site packages\pandas\core\index\range.py(self、key、method、tolerance)
356除ValueError作为错误外:
357从err升起钥匙错误(钥匙)
-->358升起钥匙错误(钥匙)
359 return super().get_loc(键,方法=方法,公差=公差)
360
键错误:“CFR Cluj”
注意:我试图交换“Rk”和“Squad”列,但没有得到任何结果,只是不同的错误
我要寻找的是从我在最终表格(排名)中找到的比赛历史记录中获得每个主队/客队的排名,并将其存储在“主队排名”/“客队排名”变量中
PS:我尝试了其他的方法来获得这个等级,但是没有一个能给我带来任何结果
任何想法或解决方案都很棒!谢谢:)关键错误反映了您试图用行值而不是列名为数据帧
排名
编制索引。您可以尝试使用
一步一步地,这等于
boolean_indices = standings['Squad']=='CFR Cluj'
standings_ranks = standings['Rk']
home_ranks = standings_ranks[boolean_indices]
home_rank = home_ranks[0] #if unique it only contains a single value
我猜您是从文件
standings.csv
创建了一个数据框standings
。我假设,可以使用列名band
,Rk
等来访问数据框standings
,比如standings['band']
。但是,该错误显示您试图评估列排名['CFR Cluj']
(KeyError)。没错,我正在从csv表创建一个数据帧。当我在历史记录csv中遇到“团队”时,如何访问包含该团队的行?。如果它是‘CFR Cluj’,我想得到它的排名,并将它的排名与其他球队的排名进行比较。我也尝试过这种方法,但最终没有效果。当我的第一个专栏是“Rk”时,我试过这个。好的。我添加了上面的内容,得到了类型错误:无法将序列转换为。还铸造了“home_rank”和“visi”
boolean_indices = standings['Squad']=='CFR Cluj'
standings_ranks = standings['Rk']
home_ranks = standings_ranks[boolean_indices]
home_rank = home_ranks[0] #if unique it only contains a single value