欢迎这位怪蜀黍来到《Python机器学习(九十四)Pandas 访问行数据 - 大码王 - 博客园》

关闭页面特效

访问行数据,有两个方法:

  • .loc – 使用索引名定位
  • .iloc – 使用索引序号定位

示例中的数据以电影名作为索引:

复制代码
# 加载数据
movies_df = pd.read_csv("IMDB-Movie-Data.csv", index_col="Title")
movies_df.columns = ['rank', 'genre', 'description', 'director', 'actors', 'year', 'runtime', 
                     'rating', 'votes', 'revenue_millions', 'metascore']

# 访问行数据
prom = movies_df.loc["Prometheus"]

prom
复制代码

输出

复制代码
rank                                                                2
genre                                        Adventure,Mystery,Sci-Fi
description         Following clues to the origin of mankind, a te...
director                                                 Ridley Scott
actors              Noomi Rapace, Logan Marshall-Green, Michael Fa...
year                                                             2012
runtime                                                           124
rating                                                              7
votes                                                          485820
revenue_millions                                               126.46
metascore                                                          65
Name: Prometheus, dtype: object
复制代码

也可以使用iloc访问电影”Prometheus”的行,”Prometheus”索引序号是1。

prom = movies_df.iloc[1]

lociloc的操作类似于Python列表切片。例如,我们可以选择多行:

movie_subset = movies_df.loc['Prometheus':'Sing']

movie_subset = movies_df.iloc[1:4]

movie_subset

输出

            rank                     genre  ... revenue_millions metascore
Title                                       ...
Prometheus     2  Adventure,Mystery,Sci-Fi  ...           126.46      65.0
Split          3           Horror,Thriller  ...           138.12      62.0
Sing           4   Animation,Comedy,Family  ...           270.32      59.0

[3 rows x 11 columns]

使用.loc.iloc选择多行操作,它们的一个重要区别是,.loc结果中包含了影片Sing,.iloc的结果中不包含索引4 (Suicide Squad)。

使用.iloc进行切片与使用列表进行切片遵循相同的规则,不包括结束索引。

 posted on   大码王  阅读(578)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具

成都

复制代码

喜欢请打赏

扫描二维码打赏

了解更多

点击右上角即可分享
微信分享提示