hider

数据分析过程中,有时出于增强数据可读性或其他原因,需要对数据表的索引值进行设定。

pandas 中,常用 set_index()reset_index() 这两个方法进行索引设置。

一、set_index方法

1.介绍

set_index() 方法将 DataFrame 中的列转化为行索引。

转换之后,原来的列将不见,可以通过设置 drop 保留原来的列。

使用语法为:

DataFrame.set_index(keys, drop=True, append=False, inplace=False, verify_integrity=False)

参数解释:

keys -- 列标签或列标签/数组列表 需要设置为索引的列
drop -- 默认为True 删除用作新索引的列
append -- 是否将列附加到现有索引 默认为False
inplace -- 布尔类型 表示当前操作是否对原数据生效 默认为False
verify_integrity -- 检查新索引的副本 将其设置为False将提高该方法的性能 默认为false

2.实操

import pandas as pd
df = pd.DataFrame({\'a\':range(7),
                   \'b\':range(7,0,-1),
                   \'c\':[\'one\',\'one\',\'one\',\'two\',\'two\',\'two\',\'two\'],
                   \'d\':[0,1,2,0,1,2,3]})

# 1.保留索引值
df.set_index([\'c\',\'d\'], drop=False) 

# 2.添加到原有索引
df.set_index(\'c\', append=True)

# 3.多重索引
df.set_index([\'c\',\'d\'])

# 4.修改原数据框
df.set_index([\'c\',\'d\'], inplace=True)

# 5.手动指定
df.set_index([pd.Index([1,2,3,4,5,6,7]), \'c\'])

# 6.索引计算
s = pd.Series([1,2,3,4,5,6,7])
df.set_index([s, s**2])

二、reset_index方法

1.介绍

reset_index() 方法用于重新设置 DataFrame 索引。

使用语法为:

DataFrame.reset_index(level=None, drop=False, inpalce=False, col_level=0, col_fill=\' \')

参数解释:

level -- 数值类型 int、str、tuple或list 
         默认无 删除所有级别的索引
         指定level 删除指定级别
drop -- 当指定 drop=False 时,则索引列会被还原为普通列;否则,经设置后的新索引值被会丢弃 默认为False
inplace -- 布尔类型 是否修改原始数据框 默认False
col_level -- 数值类型 int、str 默认值为0
             如果列有多个级别,则确定将标签插入到哪个级别。默认情况下,它将插入到第一级。
             (指定重置后的级别)
col_fill -- object 默认‘’,如果列有多个级别,则确定其他级别的命名方式。如果没有,则重复索引名。

2.实操

import pandas as pd
import numpy as np
df = pd.DataFrame({\'Country\':[\'China\',\'China\', \'India\', \'India\', \'America\', \'Japan\', \'China\', \'India\'], 
                   \'Income\':[10000, 10000, 5000, 5002, 40000, 50000, 8000, 5000], 
                    \'Age\':[50, 43, 34, 40, 25, 25, 45, 32]})

df_new = df.set_index(\'Country\', drop=True, append=False, inplace=False)

# 索引的列被还原
df_new.reset_index() # drop=False
df_new.reset_index(drop=True) # 列被删除

# 原始数据框操作
df.reset_index(drop=True)
df.reset_index()

在原有的索引列重置索引,同时不另外添加新列。

常用于索引的重置,特别在进行数据删减处理的时候派上用场。

df = pd.DataFrame(columns=[\'a\', \'b\'])
print(df)
print("---------")
b = pd.Series([1,1,1,1,1],index=[0,1,3,4,5])
a = pd.Series([2,2,2,2,2,2],index=[1,2,3,4,6,7])
df[\'a\'] = a
df[\'b\'] = b
print(df)

空数据框,只有列索引,没有数据,引用 Series 数据时,不存在的 index 可能会出现 NaN 值,甚至出现错误提示:ValueError: cannot reindex from a duplicate axis 。此时需要 reset_index() 进行索引重置。

  • 复合索引 & 复合列名
# 构建
index = pd.MultiIndex.from_tuples([(\'bird\', \'falcon\'),
                                   (\'bird\', \'parrot\'),
                                   (\'mammal\', \'lion\'),
                                   (\'mammal\', \'monkey\')],
                                  names=[\'class\', \'name\'])
columns = pd.MultiIndex.from_tuples([(\'speed\', \'max\'),
                                     (\'species\', \'type\')])
df = pd.DataFrame([(389.0, \'fly\'),
                   ( 24.0, \'fly\'),
                   ( 80.5, \'run\'),
                   (np.nan, \'jump\')],
                  index=index,
                  columns=columns)
\'\'\'
               speed species
                 max    type
class  name                 
bird   falcon  389.0     fly
       parrot   24.0     fly
mammal lion     80.5     run
       monkey    NaN    jump
\'\'\'

# 等同于 level=0
df.reset_index(level=\'class\') 

# col_level=1 指定重置后列的级别
df.reset_index(level=\'class\', col_level=1)  

# col_fill 填充缺失的列级别
df.reset_index(level=\'class\', col_level=0, col_fill=\'species\') 

# 不存在的标签 将被新建
df.reset_index(level=\'class\', col_level=0, col_fill=\'xxx\') 

reset_index()set_index() 方法可以无限制的交叉使用,灵活转变 DataFrame 索引,以方便数据处理。

参考链接:pandas中的set_index( )函数

参考链接:如何在pandas中使用set_index( )与reset_index( )设置索引

参考链接:pandas.DataFrame.set_index

参考链接:pandas重置DataFrame或Series的索引index

参考链接:pandas.DataFrame.reset_index

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-31
猜你喜欢
  • 2022-12-23
  • 2021-10-11
  • 2021-04-10
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案