reset_index()
时间: 2024-06-01 21:12:04 浏览: 61
reset_index() is a method in pandas library that is used to reset the index of a DataFrame to the default integer index. It can be used to remove the current index and replace it with a new one that contains consecutive integers starting from 0. This method does not modify the original DataFrame, but returns a new DataFrame with the reset index.
Syntax:
DataFrame.reset_index(level=None, drop=False, inplace=False, col_level=0, col_fill='')
Parameters:
level: It is an integer or a list of integers that represents the level(s) to be reset. By default, all levels are reset.
drop: It is a Boolean value that indicates whether to drop the current index or not. By default, it is False.
inplace: It is a Boolean value that indicates whether to modify the DataFrame in place or return a new DataFrame with the reset index. By default, it is False.
col_level: It is an integer or string that represents the column level to be reset. By default, it is 0.
col_fill: It is a scalar or dict-like object that is used to fill the missing values in the column index. By default, it is an empty string.
Example:
import pandas as pd
data = {'name': ['John', 'Mary', 'Peter', 'David'],
'age': [22, 27, 31, 25],
'salary': [25000, 35000, 45000, 55000]}
# create a DataFrame
df = pd.DataFrame(data)
# set the index
df.set_index('name', inplace=True)
# reset the index
df.reset_index(inplace=True)
print(df)
Output:
name age salary
0 John 22 25000
1 Mary 27 35000
2 Peter 31 45000
3 David 25 55000
阅读全文