一 set_index()函数
1 主要是理解drop和append参数,注意与reset_index()参数的不同.
import pandas as pd df = pd.DataFrame({'a': range(4), 'b': range(4, 0, -1), 'c': ['one', 'one', 'two', 'two'], 'd': ['a','b','c','d']}) print(df) # a b c d # 0 0 4 one a # 1 1 3 one b # 2 2 2 two c # 3 3 1 two d # set_index()的drop参数默认为True,如下即默认将普通列c列置为索引列后,将原先的普通列c列删除. # 注意它与reset_index()的drop不同,reset_index()中的drop默认为False,且这个drop为True时,删除的是原先的index列 df.set_index(['c'], inplace=True) print(df) # a b d # c # one 0 4 a # one 1 3 b # two 2 2 c # two 3 1 d # append参数为True,会保留原先的索引,为False时,新设置的索引会覆盖原先的索引,它类似与reset_index()中的drop. df.set_index(['b'], inplace=True, append=True) print(df) # a d # c b # one 4 0 a # 3 1 b # two 2 2 c # 1 3 d