concept iloc in category pandas

appears as: The iloc, iloc
Pandas in Action MEAP V07

This is an excerpt from Manning's book Pandas in Action MEAP V07.

The iloc (index location) attribute extracts one or more rows by index position. It accepts either a single integer for one record or a list of integers for multiple records.

In the next section, we'll take a look at how we can extract one or more rows and columns from a MultiIndex DataFrame with familiar accessor attributes like loc and iloc. As mentioned earlier, it's optimal to have our index sorted before looking up any row. The sort_index method includes the familiar inplace parameter to mutate the existing DataFrame instead of returning a new one. Let's use it now to permanently sort all levels in the MultiIndex in ascending order.

7.4.3   Extracting One or More Rows with iloc

The iloc accessor attribute extracts a row, column or value by index position rather than by label. Similar rules of indexing apply to MultiIndex DataFrames as with plain Index DataFrames. Most of these examples should be a reminder of concepts previously covered in Chapter 7.

We can pass in a single index position to iloc to pull out a single row.

In  [61] neighborhoods.iloc[25]
 
Out [61] Category  Subcategory
Culture   Restaurants    A+
          Museums         A
Services  Police         A+
          Schools        C+
Name: (CT, East Jessicaland, 208 Todd Knolls), dtype: object

We can pass two arguments to iloc to pull out the value at the intersection of a specific row and a specific column. The next example targets the row with index position 25 and the column with index position 2.

In  [62] neighborhoods.iloc[25, 2]
 
Out [62] 'A+'
 
Multiple rows can be pulled out by wrapping their index positions in a list.
 
In  [63] neighborhoods.iloc[[25, 30]]
 
Out [63]
 
Category                                  Culture         Services       
Subcategory                           Restaurants Museums   Police Schools
State City            Street______________________________________________                                             
CT    East Jessica... 208 Todd Knolls          A+       A       A+      C+
DC    East Lisaview   910 Sandy Ramp           A-      A+        B       B

There's a big difference between loc and iloc when it comes to slicing. When index slicing with iloc, the endpoint is exclusive. Note from the previous example that the record with a street of "910 Sandy Kamp" has index position 30. When we provide 30 as the endpoint in the next example, Pandas pulls up to that row but does not include it.

sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest