Pandas reset index doesn't seem to work?

前端 未结 4 487
星月不相逢
星月不相逢 2020-12-08 10:52

I\'m not sure where I am astray but I cannot seem to reset the index on a dataframe.

When I run test.head(), I get the output below:

相关标签:
4条回答
  • 2020-12-08 10:59

    reset_index by default does not modify the DataFrame; it returns a new DataFrame with the reset index. If you want to modify the original, use the inplace argument: df.reset_index(drop=True, inplace=True). Alternatively, assign the result of reset_index by doing df = df.reset_index(drop=True).

    0 讨论(0)
  • 2020-12-08 11:06

    BrenBarn's answer works.

    The following also worked via this thread, which isn't a troubleshooting so much as an articulation of how to reset the index:

    test = test.reset_index(drop=True)
    
    0 讨论(0)
  • 2020-12-08 11:16

    As an extension of in code veritas's answer... instead of doing del at the end:

    test = test.reset_index()
    del test['index']
    

    You can set drop to True.

    test = test.reset_index(drop=True)
    
    0 讨论(0)
  • 2020-12-08 11:17

    I would add to in code veritas's answer:

    If you already have an index column specified, then you can save the del, of course. In my hypothetical example:

        df_total_sales_customers = pd.DataFrame({'Sales': total_sales_customers['Sales'],
                                  'Customers': total_sales_customers['Customers']}, index = total_sales_customers.index)
    
        df_total_sales_customers = df_total_sales_customers.reset_index()
    
    0 讨论(0)
提交回复
热议问题