Label vs. Location
The main distinction between the two methods is:
To demonstrate, consider a series s
of characters with a non-monotonic integer index:
>>> s = pd.Series(list("abcdef"), index=[49, 48, 47, 0, 1, 2])
49 a
48 b
47 c
0 d
1 e
2 f
>>> s.loc[0] # value at index label 0
'd'
>>> s.iloc[0] # value at index location 0
'a'
>>> s.loc[0:1] # rows at index labels between 0 and 1 (inclusive)
0 d
1 e
>>> s.iloc[0:1] # rows at index location between 0 and 1 (exclusive)
49 a
Here are some of the differences/similarities between s.loc
and s.iloc
when passed various objects:
<object> |
description |
s.loc[<object>] |
s.iloc[<object>] |
0 |
single item |
Value at index label 0 (the string 'd' ) |
Value at index location 0 (the string 'a' ) |
0:1 |
slice |
Two rows (labels 0 and 1 ) |
One row (first row at location 0) |
1:47 |
slice with out-of-bounds end |
Zero rows (empty Series) |
Five rows (location 1 onwards) |
1:47:-1 |
slice with negative step |
three rows (labels 1 back to 47 ) |
Zero rows (empty Series) |
[2, 0] |
integer list |
Two rows with given labels |
Two rows with given locations |
s > 'e' |
Bool series (indicating which values have the property) |
One row (containing 'f' ) |
NotImplementedError |
(s>'e').values |
Bool array |
One row (containing 'f' ) |
Same as loc |
999 |
int object not in index |
KeyError |
IndexError (out of bounds) |
-1 |
int object not in index |
KeyError |
Returns last value in s |
lambda x: x.index[3] |
callable applied to series (here returning 3rd item in index) |
s.loc[s.index[3]] |
s.iloc[s.index[3]] |
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…