【pandas笔记】loc和Iloc区别

本文主要对比介绍pandas中的lociloc两个基于索引的取值方式。

iloc的意思是基于索引(index-based selection),输入为索引,也就是,行是(0,1,2,3,4)中的值,列是(0,1,2)中的值。
loc的意思是基于标签(label-based selection),输入为标签,也就是,行是(0,1,2,3,4)中的值,列是('a', 'b' ,'c')中的值。

>>> import pandas as pd
>>> df = pd.DataFrame([[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]],
                      columns=['a', 'b', 'c'])
>>> df                      
   a  b  c
0  1  2  3
1  2  3  4
2  3  4  5
3  4  5  6

# iloc取值
>>> df.iloc[0, 1]
2

# loc取值
>>> df.loc[0, 'a']
2

# 切片,前闭后开区间,结果中第一列是index
>>> df.iloc[0:2, 1]
0    2
1    3
Name: b, dtype: int64

# 切片,前闭后闭区间,结果中第一列是index
>>> df.iloc[0:2, 1]
0    1
1    2
2    3
Name: a, dtype: int64

注意

lociloc在切片时,范围的区间有些许差别。

iloc中范围是前闭后开区间
loc中范围是前闭后闭区间

你可能感兴趣的:(【pandas笔记】loc和Iloc区别)