The iloc indexing method from the DataFrame object works in the same way as numerical indexing works in two-dimensional NumPy arrays. The code illustrates several possibilities, explained in detail as follows:
- df.iloc[2] selects the row with index 2. As usual, indexing starts at 0, so the third row in the DataFrame is returned. It returns a Series objects that has the column names as indexes.
- df.iloc[:,1] selects the column with index 1, which in our example is labeled inventory. It returns a Series object with indexes identical to the row indexes in the original DataFrame.
- df.iloc[3,1] returns a single item from the DataFrame, the item at row three and column one.
- df.iloc[0:2, 1:] selects a subset from the DataFrame using ranges. The meaning of the ranges is the same as the case of NumPy arrays.
- df.iloc[[1,2],[0,2]] selects a subset from the DataFrame using lists as indexes. This particular example selects the elements where the rows at positions [1,2] intersect the columns at positions [0,2].