from pandas import Series,DataFrameimport pandas as pd
pandas 的索引对象负责管理轴标签和其他元数据(比如轴名称等)。构建Series或DataFrame时,所用到的任何数组或其他序列的标签都会被转换成一个Index:
In [3]:
obj = Series(range(3),index=['a','b','c'])index = obj.indexindex
Out[3]:
Index(['a', 'b', 'c'], dtype='object')
In [4]:
index[1:]
Out[4]:
Index(['b', 'c'], dtype='object')
Index对象是不可修改的,因此用户不能对其进行修改:
In [5]:
# 下面的语句会报错index[1] = 'd'
---------------------------------------------------------------------------TypeError Traceback (most recent call last) in ----> 1 index[1] = 'd'~/venv/science/lib/python3.8/site-packages/pandas/core/indexes/base.py in __setitem__(self, key, value) 3907 3908 def __setitem__(self, key, value):-> 3909 raise TypeError("Index does not support mutable operations") 3910 3911 def __getitem__(self, key):TypeError: Index does not support mutable operations
In [25]:
# 但是你可以这样来指定索引obj.index = Series(['a','d','c'])obj
Out[25]:
a 0d 1c 2dtype: int64
不可修改性非常重要,因为这样才能使Index对象在多个数据结构之间安全共享:
In [6]:
import numpy as npindex = pd.Index(np.arange(3))obj2 = Series([1.5,-2,0],index=index)obj2.index is index
Out[6]:
True
pandas中主要的Index对象,如下表所示:
![6afe32f6288bb4fe27ed8ad553d5478c.png](https://i-blog.csdnimg.cn/blog_migrate/521acc3a8791de2364d8f8507e06eae3.jpeg)
除了长得像数组,Index的功能也类似一个固定大小的集合:
In [17]:
frame = DataFrame({'Nevada':{2000:2.3,2001:2.4,2002:2.9}, 'Ohio':{2000:1.5,2001:1.7,2002:3.6}})frame
Out[17]:
![b011c9951df42557d353551dbf8cece3.png](https://i-blog.csdnimg.cn/blog_migrate/6ac2137e2bea438447cb689816270d0d.jpeg)
In [20]:
'Ohio' in frame.columns
Out[20]:
True
In [22]:
2003 in frame.index
Out[22]:
False
每个索引都有一些方法和属性,他们可用于设置逻辑并回答有关该索引所包含的数据的常见问题。
Index的方法和属性,如下表所示:
![69aa7dc54e0c1204a8845ea7d58b9880.png](https://i-blog.csdnimg.cn/blog_migrate/d51ce2608817f93e8151c7379f71b3a9.jpeg)