Pandas整數索引

2021-10-02 11:19:18 字數 1982 閱讀 5560

在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 "", line 1, in 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

pandas索引物件

python for data analysis index物件是不可修改的 immutable 這樣才能使index物件在多個資料結構之間安全共享。in 1 import pandas as pd in 2 from pandas import series,dataframe in 3 impo...

pandas 索引切片

ser1 pd.series range 10,15 index list abcde print ser1 普通索引 print ser1 a print ser1 0 print 注意通過自定義索引的左閉右閉的,用預設索引 下標 是左閉右開的 print ser1 a c print ser1 ...

pandas 索引筆記

1 import pandas as pd 2import numpy as np 34 s pd.series np.random.rand 5 index list abcde 5 建立序列,其中 index list abcde 為每一行新增索引 6 s.index.name alpha 為行...