5 months ago

## Pandas loc vs iloc

The general format of selecting items within a Dataframe looks like this:

When both row_index and col_index are specified, the methods loc and iloc differ in the following ways:

• You cannot use slicing or a list of integers for the col_index in the loc method.
• You cannot use labels (i.e. string) for the col_index in the iloc method.

You can use slicing or a list of integers for the row_index in both loc and iloc, but they differ:

### Returned data type

Depending on what you passed into the methods, you get different data types back:

The same rule applies to the loc method. So to sum it up:

• If both row_index and col_index are a list or slicing, then you will get a DataFrame back
• If either row_index or col_index is a list or slicing, then you will get a Series back
• If none of row_index or col_index is a list or slicing, then you will get whatever is stored in that cell back

If only the row_index is specified, the same rule applies, an integer will return a Series object, a list or slicing will return a DataFrame object:

### When to use which method

• If all of your indexes are integers, slicing or a list of integers, use iloc (that is perceisily what the i stands for)
• If you want to use Strings for the column names, use loc

The only caveat is when using slicing for the row_index in loc is that 0:2 yeilds 0,1,2, but for the iloc methods, it yeilds 0,1 (which is how slicing works everywhere else in python)