How are iloc and loc different?
Select by the integer index using iloc
: df.iloc[0]
fetches the first row. Choose by the label with loc
: df.loc['index_label']
gets the row with the label 'index_label'. When slicing, iloc
excludes the end point and loc
includes it. Explore further to master these essential pandas tools!
In-depth explanation
Basic usage: Indexing
iloc
uses integer-based indexing, similar to accessing lists, while loc
uses label-based indexing, just like using keys in dictionaries.
Slicing: The start, the end, and everything in between
When slicing, using loc
includes the end point, while iloc
does not.
Advanced slicing: Mixing label and position-based retrieval
The method get_loc()
helps to get label positions, keeping iloc
functionally high.
Sorting and indexing
iloc
indexing is not influenced by DataFrame sorting. loc
, however, adheres to the order!
Filters: Boolean vectors vs positional integers
loc
supports Boolean vectors for filtering, while iloc
loves integers.
Non-integer indexes: String and DateTime
loc
shines bright with non-integer indexes such as DateTime or strings.
Accessing all dimensions
To select all rows or columns, both iloc
and loc
utilize colon :
Single column treasure
The good old indexing operator []
serves as a shortcut for single column retrieval.
Consistent access vs order-sensitive retrieval
iloc
gives consistent results based on positions, unaffected by DataFrame order unlike loc
.
Was this article helpful?