Skip to content

reset_index() 是 Pandas 中 DataFrame 或 Series 的一个方法,用于 重置索引,也就是把当前的索引还原为默认的整数索引(0, 1, 2,...)。


基本作用:

  • 将原索引(如多级索引、非数字索引等)变成普通列
  • 新的索引将变为默认整数索引。

示例解释:

示例 1:基础用法

python
import pandas as pd

df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}, index=['x', 'y'])
print(df)

输出:

   A  B
x  1  3
y  2  4
python
df_reset = df.reset_index()
print(df_reset)

输出:

  index  A  B
0     x  1  3
1     y  2  4

原来的索引 x, y 被移到了新的一列 index,行索引变为默认的 0 和 1。


示例 2:drop=True 只重置,不保留原索引列

python
df_reset = df.reset_index(drop=True)

输出:

   A  B
0  1  3
1  2  4

原来的索引被 完全丢弃,只保留数据部分。


示例 3:对 groupby 结果使用 reset_index

python
df = pd.DataFrame({
    'group': ['A', 'A', 'B', 'B'],
    'value': [10, 20, 30, 40]
})

grouped = df.groupby('group').sum()
print(grouped)

输出:

       value
group       
A         30
B         70
python
grouped.reset_index()

输出:

  group  value
0     A     30
1     B     70

group 从索引变回了普通列。


常用参数

参数名类型说明
dropbool,默认 False是否丢弃原索引,不作为列保留。
levelint、str 或 list,默认 None如果是多级索引,指定只重置哪一级索引。
inplacebool,默认 False是否原地修改 DataFrame,不返回新对象。
nameslist,默认 None设置新插入的列的名称。

总结

场景用法
把索引变成列df.reset_index()
重设索引但不保留原索引列df.reset_index(drop=True)
对 groupby 或多级索引结果恢复成普通表reset_index()