Python Tutorial : Indexing DataFrames

Learn to index Pandas DataFrames using square brackets, .loc for label-based selection, and .iloc for position-based selection. Examples include retrieving specific values like SALT sold in January and reordering columns with nested bracket notation like df[["salt", "eggs"]].
Chapters
Pandas dataframes provide several flexible means of indexing into subsets of our data. Let's start by importing Pandas. We then read in a small data frame of sales data. The simplest indexing style uses square brackets, just as we would use to index Python lists and numpy arrays. For example, in the code shown here, we select with left bracket column label right bracket first followed by left bracket, row label right bracket. Thus, here we select SALT sold in January. Columns may also be referred to as attributes of the dataframe if their labels are valid Python identifiers Here we select eggs sold in March with df left bracket march right bracket A more efficient and more programmatically reusable way of accessing data in a data frame is by using accessors. These include LOC and iloc. The difference between the LOC and ILOC accesses is that the former accesses using labels and the latter using index positions. Both accessors use left bracket, row specifier, comma, column specifier, right bracket, and syntax. For instance, here we select spam sold in May using DF loc. On the other hand, here we select the Same entry using ILOG4. 2. Remember, list and array type structures in Python use zero based indexing. When using bracket indexing without the LOC or the ILOC accesses, the result returned can be an individual value, a PANDAS series, or a PANDAS dataframe. To ensure the return value is a dataframe, use a nested list within square brackets. As an example, this call uses a list of column labels, salt, and eggs to sub select a data frame with those two columns only. Notice we swap the order of these two columns relative to the ordering in the original dataframe in the selection. Use the exercises to get some practice now in basic indexing with loc, iloc, and with brackets.
More from Richie

#359 My Best Friend is AI with Valerie Tiberius, Professor of Philosophy at University of Minnesota

How AI Agents Will Work While You Sleep | Ruslan Salakhutdinov, Professor at Carnegie Mellon

#358 How AI Agents Will Work While You Sleep | Ruslan Salakhutdinov, Professor at Carnegie Mellon







