本文主要對比介紹pandas中的loc
和iloc
兩個基于索引的取值方式。
iloc的意思是基于索引(index-based selection)桑逝,輸入為索引蜒谤,也就是山宾,行是(0,1鳍徽,2资锰,3,4)中的值阶祭,列是(0绷杜,1,2)中的值濒募。
loc的意思是基于標(biāo)簽(label-based selection)鞭盟,輸入為標(biāo)簽,也就是萨咳,行是(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
# 切片,前閉后開區(qū)間途蒋,結(jié)果中第一列是index
>>> df.iloc[0:2, 1]
0 2
1 3
Name: b, dtype: int64
# 切片猛遍,前閉后閉區(qū)間,結(jié)果中第一列是index
>>> df.iloc[0:2, 1]
0 1
1 2
2 3
Name: a, dtype: int64
注意
loc
和iloc
在切片時(shí)号坡,范圍的區(qū)間有些許差別懊烤。
iloc
中范圍是前閉后開區(qū)間
loc
中范圍是前閉后閉區(qū)間