dataframe reset index
时间: 2023-09-04 13:15:11 浏览: 37
在 Pandas 中,reset_index() 函数是用来重置索引的。当我们进行一些数据操作后,索引通常会变得混乱,这时我们可以使用 reset_index() 函数将索引重置为默认的从 0 开始的整数索引。
下面是一个示例代码:
```python
import pandas as pd
# 创建一个示例 DataFrame
df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
'C': [1, 2, 3, 4, 5, 6, 7, 8],
'D': [10, 20, 30, 40, 50, 60, 70, 80]})
# 输出原始 DataFrame
print(df)
# 重置索引
df = df.reset_index(drop=True)
# 输出重置索引后的 DataFrame
print(df)
```
在这个示例中,我们首先创建了一个示例 DataFrame,然后使用 reset_index() 函数将索引重置为默认的从 0 开始的整数索引,并将结果保存回 df 变量中。最后,我们输出了重置索引后的 DataFrame。
需要注意的是,reset_index() 函数默认会将原来的索引作为一列添加到新的 DataFrame 中,并将其命名为 'index'。如果不想保留原来的索引,可以使用 drop=True 参数。