如何解决为什么DataFrame行选择语法df [:2]有效,但如果语法df [1]不起作用?
我有以下数据:
data = pd.DataFrame(np.arange(16).reshape(4,4),index = ['Ohio','Colorado','Utah','New York'],columns = ['one','two','three','four'])
如果我运行:
data[:2]
输出将是:
one two three four
Ohio 0 1 2 3
Colorado 4 5 6 7
如果我运行:data[1]
,将出现以下错误:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
~/opt/anaconda3/lib/python3.7/site-packages/pandas/core/indexes/base.py in get_loc(self,key,method,tolerance)
2645 try:
-> 2646 return self._engine.get_loc(key)
2647 except KeyError:
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 1
During handling of the above exception,another exception occurred:
KeyError Traceback (most recent call last)
<ipython-input-81-c402bf503b75> in <module>
----> 1 data[1]
~/opt/anaconda3/lib/python3.7/site-packages/pandas/core/frame.py in __getitem__(self,key)
2798 if self.columns.nlevels > 1:
2799 return self._getitem_multilevel(key)
-> 2800 indexer = self.columns.get_loc(key)
2801 if is_integer(indexer):
2802 indexer = [indexer]
~/opt/anaconda3/lib/python3.7/site-packages/pandas/core/indexes/base.py in get_loc(self,tolerance)
2646 return self._engine.get_loc(key)
2647 except KeyError:
-> 2648 return self._engine.get_loc(self._maybe_cast_indexer(key))
2649 indexer = self.get_indexer([key],method=method,tolerance=tolerance)
2650 if indexer.ndim > 1 or indexer.size > 1:
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 1
为什么我可以运行data[:2]
但不能运行data[1]
?对我来说这没有意义。预先谢谢您:-)
解决方法
[ ]
-索引运算符查找输入的列名。
在您的示例data[1]
中,没有名称为1
的列。所以关键错误。
但是,当您在索引运算符中传递切片符号:
时,索引运算符会将行为从 “搜索列” 更改为 “根据范围搜索行”
第一部分data[:1]
是切片操作。并且在设置index = ['Ohio','Colorado','Utah','New York']
时没有默认索引(0-9 ..),这就是为什么它会给您带来关键错误的原因。
,如果您输入列名。像data['one']
一样
俄亥俄州0
科罗拉多4
犹他州8
纽约12
名称:一个,dtype:int64
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。