NJU1healer的个人博客分享 http://blog.sciencenet.cn/u/NJU1healer

博文

Python:loc和iloc的区别

已有 11235 次阅读 2020-8-28 21:22 |个人分类:Python|系统分类:科研笔记

loc和iloc的区别

pandas以类似字典的方式来获取某一列的值,比如df[‘A’],这会得到df的A列。如果我们对某一行感兴趣呢?这个时候有两种方法,一种是iloc方法,另一种方法是loc方法。loc是指location的意思,iloc中的i是指integer。这两者的区别如下:

loc:works on labels in the index.

iloc:works on the positions in the index (so it only takes integers).

也就是说loc是根据index来索引,比如下边的df定义了一个index,那么loc就根据这个index来索引对应的行。iloc并不是根据index来索引,而是根据行号来索引,行号从0开始,逐次加1。


如下代码示例:

In [1]: df = DataFrame(randn(5,2),index=range(0,10,2),columns=list('AB'))


In [2]: df

Out[2]: 

          A         B

0  1.068932 -0.794307

2 -0.470056  1.192211

4 -0.284561  0.756029

6  1.037563 -0.267820

8 -0.538478 -0.800654


In [5]: df.iloc[[2]]

Out[5]: 

          A         B

4 -0.284561  0.756029


In [6]: df.loc[[2]]

Out[6]: 

          A         B

2 -0.470056  1.192211

点滴分享,福泽你我!Add oil!



https://wap.sciencenet.cn/blog-3428464-1248307.html

上一篇:Python中@property详解
下一篇:Python中导入模块方式汇总及执行注意
收藏 IP: 211.162.81.*| 热度|

1 石晓燕

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...
扫一扫,分享此博文

全部作者的其他最新博文

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-4-19 01:17

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部