原创 | Python | set_index 和 reset_index 区别

import pandas as pd
import numpy as np

df = pd.DataFrame(np.arange(10).reshape(2,5),columns=list('abcde'))

# set_index
df.set_index('a')  # 设置a索引 

    b   c   d   e
a               
0   1   2   3   4
5   6   7   8   9

df.reset_index(['a','b']) # 设置ab两索引

        c   d   e
a   b           
0   1   2   3   4
5   6   7   8   9

df.set_index(['a','b'],drop=False)  # drop默认True

        a   b   c   d   e
a   b                   
0   1   0   1   2   3   4
5   6   5   6   7   8   9

df.set_index(['a','b'],drop=False,inplace=True)  # 覆盖df数据

        a   b   c   d   e
a   b                   
0   1   0   1   2   3   4
5   6   5   6   7   8   9

# reset_index()
df.reset_index()

    a   b   c   d   e
0   0   1   2   3   4
1   5   6   7   8   9

df.reset_index('a')

    a   c   d   e
b               
1   0   2   3   4
6   5   7   8   9

df.reset_index(['a','b']) #设置ab索引列

    a   b   c   d   e
0   0   1   2   3   4
1   5   6   7   8   9

df.reset_index(level=0) # 还原第1个index列

    a   c   d   e
b               
1   0   2   3   4
6   5   7   8   9

df.reset_index(level=1) # 还原第2个index列

    b   c   d   e
a               
0   1   2   3   4
5   6   7   8   9

df.reset_index(level=1,drop=True)  # drop 默认False

    c   d   e
a           
0   2   3   4
5   7   8   9

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。