Sunday, August 9, 2020

Subset Rows by Row Number: iloc

How to use Pandas iloc to subset Python data - Sharp Sight

iloc does the same thing as loc but is used to subset by the row index number. In our current example, iloc and loc will behave exactly the same way since the index labels are the row numbers. However, keep in mind that the index labels do not necessarily have to be row numbers.

print(df.iloc[1])

 

print(df.iloc[99])

 

Note that when we put 1 into the list, we actually get the second row, rather than the first row. This follows Python’s zero-indexed behavior, meaning that the first item of a container is index 0 (i.e., 0th item of the container). 

With iloc, we can pass in the -1 to get the last row—something we couldn’t do with loc.

print(df.iloc[-1])

 

We can also pass in a list of integers to get multiple rows. 

print(df.iloc[[0, 99, 999]])

 

The ix attribute does not work in versions later than Pandas v0.20, since it can be confusing. Nevertheless, this section quickly reviews ix for completeness. ix can be thought of as a combination of loc and iloc, as it allows us to subset by label or integer. By default, it searches for labels. If it cannot find the corresponding label, it falls back to using integer indexing.

This can be the cause for a lot of confusion, which is why this feature has been taken out. The code using ix will look exactly like that written when using loc or iloc.

# first row
df.ix[0]
# 100th row
df.ix[99]
# 1st, 100th, and 1000th rows
df.ix[[0, 99, 999]]

The loc and iloc attributes can be used to obtain subsets of columns, rows, or both. The general syntax for loc and iloc uses square brackets with a comma. The part to the left of the comma is the row values to subset; the part to the right of the comma is the column values to subset. That is, df.loc[[rows], [columns]] or df.iloc[[rows], [columns]] 

In the next post we'll explore this concept further and discuss about Subsetting Columns.

Share:

1 comment:

  1. iloc and loc are two important concepts when it comes to website accessibility. Both of them are important for making your content accessible to screen reader users.
    https://codeprozone.com/code/python/118899/iloc-and-loc.html

    ReplyDelete