看过来
《pandas 教程》 持续更新中,提供建议、纠错、催更等加作者微信: gr99123(备注:pandas教程)和关注公众号「盖若」ID: gairuo。跟作者学习,请进入 Python学习课程。欢迎关注作者出版的书籍:《深入浅出Pandas》 和 《Python之光》。
(编码题)假设你有一个如下的 pandas DataFrame,要求对索引进行设置。
import pandas as pd
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'Age': [25, 30, 35, 40],
'City': ['New York', 'Los Angeles', 'Chicago', 'Houston']
}
df = pd.DataFrame(data)
df
'''
Name Age City
0 Alice 25 New York
1 Bob 30 Los Angeles
2 Charlie 35 Chicago
3 David 40 Houston
'''
需求:
代码如下:
# df.set_index('Name', inplace=True)
df = df.set_index('Name')
'''
Age City
Name
Alice 25 New York
Bob 30 Los Angeles
Charlie 35 Chicago
David 40 Houston
'''
# 重置索引
# df.reset_index(inplace=True)
df = df.reset_index()
'''
Name Age City
0 Alice 25 New York
1 Bob 30 Los Angeles
2 Charlie 35 Chicago
3 David 40 Houston
'''
查看相关链接中的知识。
(完)
更新时间:2025-03-07 08:27:54 标签:pandas python 索引