reset_index 怎么用
时间: 2023-06-18 21:02:14 浏览: 40
`reset_index` 是 Pandas 库中的一个函数,用于将 DataFrame 的索引重置为默认的整数索引。它可以帮助我们将索引作为一列添加到 DataFrame 中,并返回一个新的 DataFrame。
一般情况下,我们使用 `reset_index` 来处理一些需要使用 DataFrame 索引的场景,例如数据聚合操作后保留索引列而不是将其作为索引。
下面是一个简单的示例:
```python
import pandas as pd
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]})
# 对 A 和 B 列进行分组求和,并重置索引
df_grouped = df.groupby(['A', 'B']).sum().reset_index()
print(df_grouped)
```
输出结果:
```
A B C D
0 bar one 2 30
1 bar three 4 40
2 bar two 6 80
3 foo one 8 80
4 foo three 8 88
5 foo two 8 110
```
在上面的代码中,我们首先创建了一个 DataFrame,然后对 A 和 B 列进行了分组求和操作,并使用 `reset_index` 函数将索引重置为默认的整数索引。最终输出了新的 DataFrame,其中包含了原始 DataFrame 中的所有列,同时还有新的一列索引列。