索引是DataFrame和Series的行标签,而且能够有一个或多个索引。若是DataFrame和Series有一个索引,称做单级别索引;若是有多个索引,称做多级别索引。索引相似于DataFrame和Sereis的一列数据,能够有多种数据类型。索引的类型有:整数索引(Numeric Index)、分类索引(Category Index)、日期时间索引(DateTime Index、Timedelta Index)、时期索引(Period Index)、范围索引(Range Index)、间隔索引(Interval Index)、多级索引(Multi-level Index)。html
多级索引(Multi-Level Index)是指序列(Series)或数据框(DataFrame)有多个索引,多级索引相似于二维关系表,也就是说,Series或DataFrame有一个相似于DataFrame结构的索引。数组
最经常使用的索引是整数索引、分类索引和日期索引。函数
用于建立索引的最基础的构造函数:ui
pandas.Index(data,dtype=object,copy,name,tupleize_cols=True)
参数注释:spa
举个例子,建立一个整数索引:rest
>>> pd.Index([1, 2, 3]) Int64Index([1, 2, 3], dtype='int64')
索引相似于二维关系表的一列,具备特定的属性:code
检查缺失值,isna() 对索引中的每一个值进行检查,当值是NA时,返回True;当值不是NA时,返回False。 notna()对索引中的每一个值进行检查,当值不是NA时,返回True;当值是NA时,返回False。htm
Index.isna(self)
Index.notna(self)
填充缺失值,用标量值来填充NA值,downcast表示向下类型兼容:对象
Index.fillna(self, value=None, downcast=None)
删除缺失值,参数how表示如何删除缺失值,有效值是any和all:blog
Index.dropna(self, how='any')
按照索引的值进行排序,可是返回索引值的下标,参数 *args和 **kwargs都是传递给numpy.ndarray.argsort函数的参数。
Index.argsort(self, *args, **kwargs)
按照索引的值进行排序,返回排序的副本,参数return_indexer 表示是否返回索引值的下标:
Index.sort_values(self, return_indexer=False, ascending=True)
举个例子,有以下索引:
>>> idx = pd.Index(['b', 'a', 'd', 'c']) Index(['b', 'a', 'd', 'c'], dtype='object')
按照索引值进行排序,返回排序索引的下标:
>>> order = idx.argsort() >>> order array([1, 0, 3, 2])
经过下标来查看索引的排序值:
>>> idx[order] Index(['a', 'b', 'c', 'd'], dtype='object')
固然,也能够直接返回已排序的索引:
>>> idx.sort_values() Index(['a', 'b', 'c', 'd'], dtype='object')
若是要返回已排序的索引和对应的下标,须要设置参数return_indexer=True:
>>> idx.sort_values(return_indexer=True) (Index(['a', 'b', 'c', 'd'], dtype='object'), array([1, 0, 3, 2], dtype=int64))
能够把索引转换为List、DataFrame、序列、数组(ndarray)等,ravel()函数用于把索引值展开成数组形式。
Index.to_list(self) Index.to_frame(self, index=True, name=None) Index.to_series(self, index=None, name=None) Index.ravel(self, order='C')
把索引值的类型转换为指定的类型:
Index.astype(self, dtype, copy=True)
对索引值能够进行一系列的操做,下面列出最经常使用的索引操做的函数:
1,返回索引值的最大值或最小值所在的索引
Index.argmin(self, axis=None, skipna=True, *args, **kwargs)
Index.argmax(self, axis=None, skipna=True, *args, **kwargs)
2,删除索引值
删除指定的索引值
Index.delete(self, loc) Index.drop(self, labels, errors='raise')
3,重复值
drop_duplicates()函数用于把重复的值删除,keep参数的有效值是first、false和False,frist表示保留第一次、last表示保留最后一次、False表示把重复的值删除。
Index.drop_duplicates(self, keep='first')
检查索引值是不是重复的,当出现重复值时,把索引值相应位置的值设置为True。
Index.duplicated(self, keep='first')
4,插入新值
Index.insert(self, loc, item)
5,重命名索引的name属性
Index.rename(self, name, inplace=False)
6,索引的惟一值
Index.unique(self, level=None)
7,获取索引的下标
第一种方式是传递索引值列表:
Index.get_indexer(self, target, method=None, limit=None, tolerance=None)
参数注释:
target:索引列表
method:None, ‘pad’/’ffill’, ‘backfill’/’bfill’, ‘nearest’
limit:在target中不能彻底匹配的连续标签的最大数量
tolerance:不能彻底匹配的原始索引和新索引之间的最大距离, 匹配位置处的索引值最知足方程 abs(index [indexer]-target)<=tolerance。
第二种方式是传递一个索引的标量值,返回该标量值在索引中的位置:
Index.get_loc(self, key, method=None, tolerance=None)
参考文档: