dataframe 行索引
时间: 2025-01-20 13:53:53 浏览: 17
修改 Pandas DataFrame 的行索引
在数据分析过程中,修改或重置 pandas
中 DataFrame
的行索引是一项常见需求。以下是几种常用的方法。
使用 reset_index()
方法重置索引
当希望将现有的索引重置为默认整数索引时,可以使用 DataFrame.reset_index()
方法[^1]:
import pandas as pd
data = {'Name': ['John', 'Emma', 'Mike', 'Sophia'],
'Age': [25, 28, 21, 24],
'City': ['New York', 'London', 'Paris', 'Tokyo']}
df = pd.DataFrame(data)
print("原始数据帧:")
print(df)
# 将索引重置为默认整数索引
new_df = df.reset_index(drop=True)
print("\n重置后的数据帧:")
print(new_df)
设置参数 drop=True
可防止旧索引作为新列被保留下来。
手动指定新的行索引标签
如果想要自定义行索引名称,则可以通过直接赋值给 index
属性来实现这一点[^2]:
custom_indices = ['one', 'two', 'three', 'four']
df.index = custom_indices
print("\n带有自定义索引的数据帧:")
print(df)
这种方法允许用户完全控制每一行对应的索引标签。
遍历并打印当前的行索引
为了查看现有数据框中的所有行及其对应索引,可利用 iterrows()
函数迭代访问每一条记录[^3][^4]:
for idx, row in df.iterrows():
print(f'Index: {idx}, Name: {row["Name"]}')
这段代码会逐条输出各行列项以及它们各自的索引位置。
相关推荐


















