我正在制作一个条形图,显示棒球运动员每年的WAR等级。我试图将条形图标记为玩家姓名(玩年数)。这是我的代码:
#Generate full names for the players: player name (years played)
full_name = []
for player, years in zip(war_data['Player'].values, war_data['yrs'].values):
full_name.append(player + " (" + str(years) + ")")
war_data["Full_Name"] = array(full_name)
fig = plt.figure(figsize=(8,12))
我的数据集名为war_data。输入war_data.head()
时输出正确,组织如下:
Player yrs WAR WAR_per_yearsplayed
0 Babe Ruth+ 22 183.8 8.354545
785 Charlie Ferguson 4 32.1 8.025000
2 Walter Johnson+ 21 165.6 7.885714
15 Kid Nichols+ 15 116.4 7.760000
1 Cy Young+ 22 168.4 7.654545
我得到的错误是:
KeyError: u'no item named Player'
提前感谢任何见解!
编辑:这是完整的追溯:
KeyError Traceback (most recent call last)
<ipython-input-6-a2cfa6bc215d> in <module>()
2 full_name = []
3
----> 4 for player, years in zip(war_data['Player'].values, war_data['yrs'].values):
5 full_name.append(player + " (" + str(years) + ")")
6
c:\Python27\lib\site-packages\pandas-0.12.0-py2.7-win-amd64.egg\pandas\core\frame.pyc in __getitem__(self, key)
2001 # get column
2002 if self.columns.is_unique:
-> 2003 return self._get_item_cache(key)
2004
2005 # duplicate columns
c:\Python27\lib\site-packages\pandas-0.12.0-py2.7-win-amd64.egg\pandas\core\generic.pyc in _get_item_cache(self, item)
665 return cache[item]
666 except Exception:
--> 667 values = self._data.get(item)
668 res = self._box_item_values(item, values)
669 cache[item] = res
c:\Python27\lib\site-packages\pandas-0.12.0-py2.7-win-amd64.egg\pandas\core\internals.pyc in get(self, item)
1653 def get(self, item):
1654 if self.items.is_unique:
-> 1655 _, block = self._find_block(item)
1656 return block.get(item)
1657 else:
c:\Python27\lib\site-packages\pandas-0.12.0-py2.7-win-amd64.egg\pandas\core\internals.pyc in _find_block(self, item)
1933
1934 def _find_block(self, item):
-> 1935 self._check_have(item)
1936 for i, block in enumerate(self.blocks):
1937 if item in block:
c:\Python27\lib\site-packages\pandas-0.12.0-py2.7-win-amd64.egg\pandas\core\internals.pyc in _check_have(self, item)
1940 def _check_have(self, item):
1941 if item not in self.items:
-> 1942 raise KeyError('no item named %s' % com.pprint_thing(item))
1943
1944 def reindex_axis(self, new_axis, method=None, axis=0, copy=True):
KeyError: u'no item named Player'
答案 0 :(得分:3)
[移出评论。]
可能有你看不到的空白。 print war_data.columns
要检查。例如:
>>> df = pd.DataFrame({"A ": [1,2,3], "B": [2,3,4]})
>>> df
A B
0 1 2
1 2 3
2 3 4
[3 rows x 2 columns]
>>> df.columns
Index([u'A ', u'B'], dtype='object')
>>> df["A"]
Traceback (most recent call last):
[...]
KeyError: u'no item named A'