pandas 学习 第8篇:Index 对象

Index对象负责管理轴标签、轴名称等元数据,是一个不可修改的、有序的、可以索引的ndarry对象。在构建Sereis或DataFrame时,所用到的任何数据或者array-like的标签,都会转换为一个Index对象。Index对象是一个从索引到数据值的映射,当数据是一列时,Index是列索引;当数据是一行数据时,Index是行索引。

一,基础函数

用于创建索引的最基础的构造函数:

pandas.Index(data,dtype=object,name)

参数注释:

  • data:类似于一维数组的对象
  • dtype:用于设置索引元素的类型,默认值是object
  • name:索引的名称,默认值是Index

举个例子,创建一个整数索引:

>>> pd.Index([1, 2, 3])
Int64Index([1, 2, 3], dtype='int64')

索引是一个ndarray对象,元素的类型相同,每一个Index对象,常用的属性有:

  • values:索引的值
  • array:以数组形式返回索引元素的值
  • dtype:索引元素的数据类型
  • name:索引的名称属性
  • shape:索引的形状

二,索引的转换

索引是一个ndarray对象,不仅元素类型可以转换,其对象本身也可以强转为其他like-array类型,比如list、Series和DataFrame。

1,强转索引值的类型

显式把索引元素的类型强制转换成其他数据类型:

Index.astype(self, dtype, copy=True)

2,把索引转换成list

list是由索引的值构成的:

Index.to_list(self)

3,把索引转换成Series

Series的索引值和数据值相同,是由原索引的数据值构成的:

Index.to_series(self, index=None, name=None)

参数index 表示新建Sereis的索引,默认值是None,表示新建Sereis的索引就是原索引。

>>> idx = pd.Index(['Ant', 'Bear', 'Cow'], name='animal')
>>> idx.to_series()
animal
Ant      Ant
Bear    Bear
Cow      Cow
Name: animal, dtype: object

4,把索引转换成DataFrame

创建一个新的DataFrame对象,列的值是由索引值构成的,默认情况下,新DataFrame的索引就是原索引:

Index.to_frame(self, index=True, name=None)

参数index表示是否把原索引作为新创建的DataFrame对象的索引,默认值是True。

>>> idx = pd.Index(['Ant', 'Bear', 'Cow'], name='animal')
>>> idx.to_frame()
       animal
animal
Ant       Ant
Bear     Bear
Cow       Cow

5,把索引展开为ndarray对象

该方法和numpy.ravel() 相同,把Index对象展开为一维的ndarray对象:

Index.ravel(self, order='C')

三,索引的排序

按照索引的值进行排序,但是返回索引值的下标,参数 *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))

参考文档:

pandas index

原文地址:https://www.cnblogs.com/ljhdo/p/11556410.html