文章目录
数据分析.pandas.索引及复合索引
一、索引(index)
pandas的索引对象负责管理轴标签和其他元数据(比如轴名称等)。构建Series或DataFrame时,被作为索引的数组会被转换成一个Index:
除了类似于数组,Index也具有set集合的功能:
与python的集合不同,pandas的Index可以包含重复的标签,选择重复的标签,会显示所有的结果。
下面是Index对象主要的方法和属性:
返回顶部
二、重建索引(reindex)
pandas对象的reindex方法作用是重建新的索引。
method选项可填入的参数包括 : {None, ‘backfill’/‘bfill’, ‘pad’/‘ffill’, ‘nearest’}
默认为None: 不进行填充
pad/ffill: 前向填充,使用前面的有效值进行填充
backfill/bfill: 后向填充,使用后面有效值进行填充
nearest: 使用最近的有效值进行填充
列可以用columns关键字重新索引:
借助DataFrame,reindex可以修改(行)索引和列。只传递一个序列时,会重新索引结果的行:
返回顶部
三、复合索引
索引可以包含一个、两个或多个列。两个或更多个列上的索引被称作复合索引。
pandas中set_index方法是专门用来将某一列设置为index的方法。它具有简单,方便,快捷的特点。
主要参数:
keys:
需要设置为index的列名
drop:
True or False。在将原来的列设置为index,是否需要删除原来的列。默认为True,即删除(Delete columns to be used as the new index.)
append:
True or False。新的index设置之后,是否要删除原来的index。 默认为True。(Whether to append columns to existing index.)
inplace:
True or False。是否要用新的DataFrame取代原来的DataFrame。默认False,即不取代。**( Modify the DataFrame in place (do not create a new object))
返回顶部
四、Series、DataFrame复合索引的操作
上面我们提过,pandas的Index可以包含重复的标签,选择重复的标签,会显示所有的结果,如上面案例所示,在设置dataframe表时,我们设置c列包含有重复的值,当我们设置c、d列为索引时,自动去重,并在对应d列首个内层索引处显示出外层唯一索引。
返回顶部