Pandas整数索引

在pandas上使用整数索引容易产生歧义,因为它和在列表、元组内构建数据结构进行索引有一点不同。
1.整数索引
如下代码

ser = pd.Series(np.arange(3.))
ser[-1]

返回的结果为:

Traceback (most recent call last):
  File "G:\soft\anaconda\install\lib\site-packages\IPython\core\interactiveshell.py", line 2885, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-22-3cbe0b873a9e>", line 1, in <module>
    ser[-1]
  File "G:\soft\anaconda\install\lib\site-packages\pandas\core\series.py", line 583, in __getitem__
    result = self.index.get_value(self, key)
  File "G:\soft\anaconda\install\lib\site-packages\pandas\indexes\base.py", line 1980, in get_value
    tz=getattr(series.dtype, 'tz', None))
  File "pandas\index.pyx", line 103, in pandas.index.IndexEngine.get_value (pandas\index.c:3332)
  File "pandas\index.pyx", line 111, in pandas.index.IndexEngine.get_value (pandas\index.c:3035)
  File "pandas\index.pyx", line 159, in pandas.index.IndexEngine.get_loc (pandas\index.c:4018)
  File "pandas\hashtable.pyx", line 303, in pandas.hashtable.Int64HashTable.get_item (pandas\hashtable.c:6610)
  File "pandas\hashtable.pyx", line 309, in pandas.hashtable.Int64HashTable.get_item (pandas\hashtable.c:6554)
KeyError: -1

上述的索引引起一些错误,是因为整数索引包含了0,1,2,但是用户使用的索引不一定相同,此时会产生歧义
2.非整数索引

对于非整数索引,一般就不会产生歧义,如下文代码

ser2 = pd.Series(np.arange(3.), index=['a','b','c'])
ser2[-1]

返回结果为:

Out[23]: 2.0

3.处理整数索引数据
为保持一致性,如果有包含整数的轴索引,数据选择时最好使用标签索引。若需要精确处理,可使用loc(用于标签)或者iloc(用于整数)进行处理

loc用于轴标签,iloc用于整数标签
进行运行分析如下

ser[:1]
Out[24]: 
0    0.0
dtype: float64
ser.loc[:1]
Out[25]: 
0    0.0
1    1.0
dtype: float64
ser.iloc[:1]
Out[26]: 
0    0.0
dtype: float64

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值