Home >Backend Development >Python Tutorial >What are the key differences between Pandas' `loc` and `iloc` methods for DataFrame slicing?
iloc and loc are two methods for slicing a DataFrame in Pandas. Both methods can be used to select rows and columns, but they differ in how they interpret the input.
loc gets rows (and/or columns) with particular labels.
iloc gets rows (and/or columns) at integer locations.
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]] |
The above is the detailed content of What are the key differences between Pandas' `loc` and `iloc` methods for DataFrame slicing?. For more information, please follow other related articles on the PHP Chinese website!