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