4. Accessing and Subsetting Data

Open In Colab

Selection, Subsetting and Sorting a DataFrame

When exploring our data we will often want to modify specific rows, columns, or entries that satisfy certain conditions. We may want to either look at a single column of the data or work with a subset of the original data. Furthermore, it is often helpful to sort our data set using a particular relation to identify patterns and to understand the data’s structure. For example, suppose the original dataset we acquire and want to analyze describes a sports team’s performance for each game during a season and its original order is chronological. It may be interesting to sort the gameplay statistics using a different relation such as number of points scored to easily identify high and low-scoring games.

As with previous modules, you should follow along in the notebook, which can be opened by clicking the Open in Colab button above.

Selection

Selecting data from a DataFrame is intuitive and builds on concepts we discussed in the previous module. A DataFrame holds column names, called headers, and row names, called indexes. Depending on how we loaded the data these might be integers, strings (text) or combinations of both.

In the context of the table shown in the image below, Pandas allows us to choose specific combinations of rows and columns from the associated DataFrame. We will cover some ways to do that in the sections that follow:

/Selection%20DataFrame

Selecting Columns

To begin, let’s concentrate on subsetting columns. This operation closely resembles accessing keys in a Python dictionary. Thus, if we possess a DataFrame named df with a column labeled 'ph', we can subset the DataFrame by employing df['ph'].

Selecting Rows

If on the other hand, we want to access a subset rows we have to use a slightly different approach. Previously, we could just pass the name of the column inside brackets if we want to access one or more rows we need to use the .loc or .iloc methods.

The first abbreviation, ‘loc,’ represents ‘location’ and requires you to specify the names of the rows you wish to access. The second abbreviation, ‘iloc,’ represents ‘integer location’ and requires you to provide the row index (a numerical value). Both methods can be set to retrieve the complete row(s), or only a subset of values associated with columns of interest.

So if we again have a DataFrame called df and a row called ‘Sample-1’ we can access it using df.loc['Sample-1', df.columns].

The attribute columns in the expression df.columns is used to retrieve all the header names (column labels) within the DataFrame referred to as df. It is employed above to inform Pandas that the column values within the DataFrame corresponding to the row labeled ‘Sample-1’ should be accessed.

If we were to use .iloc instead of .loc for the previous example and we know that ‘Sample-1’ is at index position 0 we would use df.iloc[0, :] and get the same result. You might notice that we also had to change df.columns to : when we used .iloc this is because df.columns provides the names of all the headers which is fine to do with .loc but not .iloc since the latter requires indexes, not names (strings).

The : operator: refresher

Selecting Columns and Rows Simultaneously

As we saw in the previous section we can select one or more rows and/or columns to view. For example, if we wanted to view the ‘ph’ entry of ‘Sample-1’ from the previous example we could use .loc in the following manner.

If we wanted to select multiple columns e.g. both the ‘ph’ and ‘Longitude’ columns we can change the code bit to fit our needs.

Using .iloc

You can just as well use .iloc for the two examples above, but you will need to change the index and headers to their respective integer values i.e. the row number(s) and the header number(s).

Subsetting

Comparison operations (“<” , “>” , “==” , “>=” , “<=” , “!=”) can be applied to pandas Series and DataFrames in the same vectorized fashion as arithmetic operations except the returned object is a Series or DataFrame of booleans (either True or False). Below are a few examples

Within a Single DataFrame

As an example lets say that we have a DataFrame like the one below stored in df:

/Selection%20DataFrame

To identify samples with a ‘pressure in dbar’ value less than 380 from the data, we begin by referencing the ‘press dbar’ column, similar to how we did it before. Subsequently, we apply a less-than condition to compare all the values in this column with the threshold of 380.

The initial rows display a value of ‘True,’ whereas the other rows show ‘False’, meaning the condition was not met. A brief inspection of the original dataset validates this alignment with our established condition. To access or store the rows identified as having a depth less than 380, we can either assign the resulting ‘Series’ to a variable for subsequent use or employ the previously applied code directly within parentheses. Both approaches yield identical results, as demonstrated below.

It might seem counterintuitive not to use .loc or .iloc even though we are selecting rows. This is due to the fact that the output of df['press dbar'] < 380 is a Pandas Series that contains information on the row and Pandas inherently assumes that when it is passed a boolean list like this that we want to select those rows that are True. A graphic example of this is shown below.

/Filter%20DataFrame

Sorting

There may also come a time when we want to see the data sorted by some criterion in order to explore potential patterns and order statistics of the entries based on a relation. For example, we might want to order a DataFrame by the depth that a sample was recovered from. Note: We can also sort the order of the columns based on their names.

There are two primary approaches for sorting a DataFrame: one based on the index and the other based on values. When sorting by the index (it’s important to note that the index can represent either row or column labels), you can utilize the sort_index() method. This method accepts an argument for the axis parameter (0 for rows, 1 for columns). In our specific case using DataFrame df, since the rows are already sorted, we can reconfigure the order of the columns instead by specifiying axis=1

Here we can see that we’ve ordered the columns alphabetically.

If we want to order the DataFrame based on the value in a particular column or row we instead use sort_values(). We can again use the pressure i.e. ‘press dbar’ column as an example and sort the rows by greatest to smallest pressure value.