The reset_index() method is a pandas function that resets the index of a dataframe. It is used to convert a series, which may have an index, into a dataframe.

Syntax:

DataFrame.reset_index(level=None, drop=False, inplace=False, col_level=0, col_fill='')

Parameters:

  • level: int, str, tuple, or list, optional. It is used to specify which level(s) of the multi-index to reset. By default, all levels are reset.
  • drop: bool, optional. It is used to remove the old index column(s) from the dataframe. By default, the old index column(s) are kept as a new column(s) in the dataframe.
  • inplace: bool, optional. It is used to modify the original dataframe instead of creating a new one. By default, a new dataframe is returned.
  • col_level: int or str, optional. It is used to specify the level(s) of the column multi-index to reset. By default, the column index is not reset.
  • col_fill: object, optional. It is used to fill the missing values with a specified value. By default, missing values are filled with NaN.

Example:

import pandas as pd

# create a sample dataframe with a multi-index
index = [('California', 2000), ('California', 2010), ('New York', 2000), ('New York', 2010)]
data = {'population': [33871648, 37253956, 18976457, 19378102], 'area': [423967, 423968, 141297, 141298]}
df = pd.DataFrame(data, index=index)
print(df)

# reset the index
df_reset = df.reset_index()
print(df_reset)

# reset the index and drop the old index column(s)
df_reset_drop = df.reset_index(drop=True)
print(df_reset_drop)

# reset the index and modify the original dataframe
df.reset_index(inplace=True)
print(df)

Output:

                    population    area
California 2000      33871648  423967
           2010      37253956  423968
New York   2000      18976457  141297
           2010      19378102  141298

        level_0  level_1  population    area
0    California     2000    33871648  423967
1    California     2010    37253956  423968
2      New York     2000    18976457  141297
3      New York     2010    19378102  141298

   population    area
0    33871648  423967
1    37253956  423968
2    18976457  141297
3    19378102  141298

       level_0  level_1  population    area
0    California     2000    33871648  423967
1    California     2010    37253956  423968
2      New York     2000    18976457  141297
3      New York     2010    19378102  141298
pandas--reset_index

原文地址: https://www.cveoy.top/t/topic/l0I 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录