随笔 - 384  文章 - 0  评论 - 35  阅读 - 142万

df.set_index() 使用现有列设置单(复合)索引,df.reset_index()还原索引

set_index

DataFrame可以通过set_index方法,可以使用现有列设置单索引和复合索引

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

参数:

  1. keys:label or array-like or list of labels/arrays,这个是需要设置为索引的列名,可以是单个列名,或者是多个列名
  2. drop:bool, default True,删除要用作新索引的列
  3. append:bool, default False,添加新索引
  4. inplace:bool, default False,是否要覆盖数据集
  5. verify_integrity:bool, default False,检查新索引是否重复。否则,将检查推迟到必要时进行。设置为False将改善此方法的性能

 

注意:drop为False,inplace为True时,索引将会还原为列

官网例子

 

复制代码
df = pd.DataFrame({'month': [1, 4, 7, 10],
                   'year': [2012, 2014, 2013, 2014],
                   'sale': [55, 40, 84, 31]})


#设置单个列作为索引
df.set_index('month')
'''
       year  sale
month
1      2012    55
4      2014    40
7      2013    84
10     2014    31
'''
#设置复合索引
df.set_index(['year', 'month'])
'''
            sale
year  month
2012  1     55
2014  4     40
2013  7     84
2014  10    31
'''
#自定义索引和某列作为复合索引
df.set_index([pd.Index([1, 2, 3, 4]), 'year'])
'''
         month  sale
   year
1  2012  1      55
2  2014  4      40
3  2013  7      84
4  2014  10     31
'''
#自定义索引
s = pd.Series([1, 2, 3, 4])
df.set_index([s, s**2])
'''
      month  year  sale
1 1       1  2012    55
2 4       4  2014    40
3 9       7  2013    84
4 16     10  2014    31
'''
复制代码

 

reset_index

多用于删除某行后重新设置0开始的索引

reset_index,重置DataFrame的索引,并使用默认索引。如果DataFrame具有MultiIndex,则此方法可以删除一个或多个级别

DataFrame.reset_index(level=None, drop=False, inplace=False, col_level=0, col_fill=”) 

参数:

  1. level:int, str, tuple, or list, default None,仅从索引中删除给定的级别。默认情况下删除所有级别
  2. drop:bool, default False,drop为False则索引列会被还原为普通列,否则会丢失
  3. inplace:bool, default False
  4. col_level:int or str, default 0,如果列有多个级别,请确定将标签插入到哪个级别。默认情况下,它被插入第一级
  5. col_fill:object, default ‘’,如果列有多个级别,请确定如何命名其他级别。如果为None,则重复索引名称

官网例子

df = pd.DataFrame([('bird', 389.0),
                   ('bird', 24.0),
                   ('mammal', 80.5),
                   ('mammal', np.nan)],
                  index=['falcon', 'parrot', 'lion', 'monkey'],
                  columns=('class', 'max_speed'))
df
         class  max_speed
falcon    bird      389.0
parrot    bird       24.0
lion    mammal       80.5
monkey  mammal        NaN

重置索引时,会将旧索引添加为列,并使用新的顺序索引:

df.reset_index()
    index   class  max_speed
0  falcon    bird      389.0
1  parrot    bird       24.0
2    lion  mammal       80.5
3  monkey  mammal        NaN

我们可以使用drop参数来避免将旧索引添加为列:

df.reset_index(drop=True)
    class  max_speed
0    bird      389.0
1    bird       24.0
2  mammal       80.5
3  mammal        NaN

也可以将reset_index与MultiIndex 一起使用。

复制代码
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)
df
复制代码
               speed species
                 max    type
class  name
bird   falcon  389.0     fly
       parrot   24.0     fly
mammal lion     80.5     run
       monkey    NaN    jump

如果索引具有多个级别,我们可以重置其中的一个子集:

df.reset_index(level='class')
         class  speed species
                  max    type
name
falcon    bird  389.0     fly
parrot    bird   24.0     fly
lion    mammal   80.5     run
monkey  mammal    NaN    jump

如果我们不删除索引,则默认情况下,它位于顶层我们可以将其放在另一个级别:

df.reset_index(level='class', col_level=1)
                speed species
         class    max    type
name
falcon    bird  389.0     fly
parrot    bird   24.0     fly
lion    mammal   80.5     run
monkey  mammal    NaN    jump

当索引插入到另一个级别下时,我们可以使用参数col_fill指定在哪个级别下

df.reset_index(level='class', col_level=1, col_fill='species')
              species  speed species
                class    max    type
name
falcon           bird  389.0     fly
parrot           bird   24.0     fly
lion           mammal   80.5     run
monkey         mammal    NaN    jump

如果我们为col_fill指定一个不存在的级别,则会创建它:

df.reset_index(level='class', col_level=1, col_fill='genus')
                genus  speed species
                class    max    type
name
falcon           bird  389.0     fly
parrot           bird   24.0     fly
lion           mammal   80.5     run
monkey         mammal    NaN    jump

 

posted on   小小喽啰  阅读(9158)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示