美文网首页
reset_index()

reset_index()

作者: tianzhanlan | 来源:发表于2020-01-07 17:04 被阅读0次

    reset_index()主要用于重置索引

    import pandas as pd
    import numpy as np
    df = pd.DataFrame(np.arange(9).reshape(3,3),index=[1,3,4])
    print(df)
       0  1  2
    1  0  1  2
    3  3  4  5
    4  6  7  8
    

    reset_index()重置索引

    print(df.reset_index())
       index  0  1  2
    0      1  0  1  2
    1      3  3  4  5
    2      4  6  7  8
    

    在获得新的index,原来的index变成数据列,保留在数据框中,不想保留原来的index的话可以使用参数drop=True,默认False。

    print(df.reset_index(drop=True))
       0  1  2
    0  0  1  2
    1  3  4  5
    2  6  7  8
    

    另外在保留的index时,可以直接用rename()函数修改index列的列名:

    print(df.reset_index().rename(columns={"index":"new"}))
       new  0  1  2
    0    1  0  1  2
    1    3  3  4  5
    2    4  6  7  8
    

    相关文章

      网友评论

          本文标题:reset_index()

          本文链接:https://www.haomeiwen.com/subject/whfdactx.html