Pandas set_index 和reset_index

set_index

函数原型:

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

  • 参数解释:
    keys–label or array-like or list of labels/arrays
    This parameter can be either a single column key, a single array of
    the same length as the calling DataFrame, or a list containing an arbitrary combination of column keys and arrays. Here, “array”
    encompasses :class:Series, :class:Index, np.ndarray, and
    instances of :class:~collections.abc.Iterator.
    列标签或者类似列表或 列标签列表,也就是需要设置为索引的列
    drop– Delete columns to be used as the new index. bool default True.默认为True,是否删除原来的索引,默认删除
    append– Whether to append columns to existing index. bool default False. 是否要把要删除的列标签加入到存在的索引中,默认否。
    inplace–Modify the DataFrame in place (do not create a new object). bool,default False.是否要创建一个新的对象,默认否。
    verify_integrity–Check the new index for duplicates. Otherwise defer the check until necessary. Setting to False will improve the performance of this method. default False. 默认为false,检查新索引的副本。否则,请将检查推迟到必要时进行。将其设置为false将提高该方法的性能。

Demo

df = DataFrame(np.random.rand(6,4),index=['a','b','c','d','e','f'],columns=['A','B','C','D'])
df

在这里插入图片描述

# drop = False  没有删除作为新索引的列,同时append=false,没有保留原来的索引
df1 =df.set_index('A',drop=False,append=False,inplace=False)
df1

在这里插入图片描述

# drop =True,删除了用作新索引的那一列,append=False没有保留原来的索引
df2 = df.set_index('A',drop=True,append=False,inplace=False)
df2

在这里插入图片描述

# append=True,将原来的索引保留了下来
df3 = df.set_index('A',drop=True,append=True,inplace=False)
df3

在这里插入图片描述
inplace = True
在这里插入图片描述
在这里插入图片描述

reset_index

函数原型:

DataFrame.reset_index(level=None, drop=False,inplace=False,col_level=0, col_fill=’’)
参数解释:
level:int、str、tuple或list,默认无,仅从索引中删除给定级别。默认情况下移除所有级别。控制了具体要还原的那个等级的索引
drop:drop为False则索引列会被还原为普通列,否则会丢失
inplace:默认为false,适当修改DataFrame(不要创建新对象)
col_level:int或str,默认值为0,如果列有多个级别,则确定将标签插入到哪个级别。默认情况下,它将插入到第一级。
col_fill:对象,默认‘’,如果列有多个级别,则确定其他级别的命名方式。如果没有,则重复索引名

  • 注:reset_index还原分为两种类型,第一种是对原DataFrame进行reset,第二种是对使用过set_index()函数的DataFrame进行reset。

Demo

df1 = DataFrame(np.random.rand(6,4),index=['a','b','c','d','e','f'],columns=['A','B','C','D'])
df1

在这里插入图片描述

df1_1= df1.set_index('A',drop=True,append=False,inplace=False)
df1_1

在这里插入图片描述

df2 = df1.reset_index(drop=False)
df2

在这里插入图片描述

df3=df1.reset_index(drop=True)
df3

在这里插入图片描述

df2_1=df1_1.reset_index(drop=True)
df2_1

在这里插入图片描述

df3_1=df1_1.reset_index(drop=False)
df3_1

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值