Introduction to Pandas

Tyler Caraza-Harter and Meenakshi Syamkumar

Many datasets you'll encounter are tabular; in other words, the data can be organized with tables and columns. We've seen how to organize this data with lists of lists, but this is cumbersome. Now we'll learn Pandas, a Python module built specifically for tabular data. If you become comfortable with Pandas, you'll likely start preferring it for analyzing tables.

Pandas gets installed via anaconda installation. In case the below import statement fails, you can paste the below command in terminal / powershell to install pandas:

pip install pandas

The as pd expression may be new for you. This just gives the pandas module a new name in our code, so we can type things like pd.some_function() to call a function named some_function rather than type out pandas.some_function(). You could also have just used import pandas or even given it another name with an import like import pandas as pnds, but we recommend you import as "pd", because most pandas users do so by convention.

We'll also be using two new data types (Series and DataFrame) from Pandas very often, so let's import these directly so we don't even need to prefix their use with pd..

Pandas Series

Pandas tables are built as collections of Pandas Series. A Series is a sophisticated data structure that combines many of the features of both Python list and dict.

You can think of a Series as a dictionary where the values are ordered and, in addition to having a key, are labeled with integer positions (0, 1, 2, etc).

Careful with the Vocabulary!

The terms we'll use when talking about Series are not very consistent with the terms we used for lists and dicts. It is good to learn the correct vocubalary, as you'll encounter the same vocabulary on websites like stackoverflow.

A pandas integer position refers to a 0, 1, 2, etc. label, and is equivalent to a list's index.

A pandas index refers to the programmer-chosen label (which could be a string, int, etc) on a value, and is equivalent to a dict's key.

Series vs. Dictionary

It is easy to convert a dict to a Series:

In this case, the values are 7, 8, and 9, and the corresponding indexes are "one", "two", and "three".

dtype stands for data type. In this case, it means that the series contains integers, each of which require 64 bits of memory (this detail is not important for us). Although you could create a Series containing different types of data (as with lists), we'll avoid doing so because working with Series of one type will often be more convenient. You may mix values of different types in a Series (just like we regularly do with lists), but this is discouraged.

A Series can be expected to keep the same order (unless we intentionally change it), unlike a dict.

Let's lookup a value using some indexes, using .loc[???]:

Instead of .loc we can use .iloc to do lookup by integer position:

We can always convert a Series back to a dict. The pandas indexes become dict keys.

Series vs. List

We can also convert back and forth between lists as Series:

Notice that both the list and the Series contain the same values. However, there are some differences:

When we create a Series from a list, there is no difference between the integer position and index. s.iloc[X] is the same as s.loc[X].

Going from a Series back to a list is just as easy as going from a list to a Series:

Indexing and Slicing

Series slicing works much like list slicing:

Be careful! Notice the indices for the slice. It is not creating a new Series indexed from zero, as you would expect with a list.

You should think of Series(["A", "B", "C"]) as being similar to this:

We can also slice a Series constructed from a dictionary (remember that you may not slice a regular Python dict):

Element-Wise Operations

Two types of element-wise operations:

With a Series, we can do the same like this:

This probably feels more intuitive for those of you familar with vector math.

It also means multiplication means something very different for lists than for Series. It replicates the list, rather than multiply each item by the int.

Whereas a "+" means concatenate for lists, it means element-wise addition for Series:

One implication of this is that you might not get what you expect if you add Series of different sizes:

The 10 gets added with the 1, and the 20 gets added with the 2, but there's nothing in the second series to add with 30. 30 plus nothing doesn't make sense, so Pandas gives "NaN". This stands for "Not a Number".

Element-wise operations produces a new Series. If you want to update the original variable, you'll have to use exclusive assignment operation.

You can also use syntactic sugar. Operators other than + and * will also work on Series.

Examples of other operators.

You can create a Series with different types, but we are not going to be using this a lot.

Series insertion

Series concatenation

Boolean Element-Wise Operation

Consider the following:

This example shows that you can do element-wise comparisons as well. The result is a Series of booleans. If the value in the original Series is greater than 5, we see True at the same position in the output Series. Otherwise, the value at the same position in the output Series is False.

We can also chain these operations together:

As you can see, we first obtained an integer Series (mod_2) by computing the value of every number modulo 2 (mod_2) will of course contain only 1's and 0's).

We then create a Boolean series (odd) by comparing the mod_2 series to 1.

If a number in the nums Series is odd, then the value at the same position in the odd series will be True.

Data Alignment

Notice what happens when we create a series from a list:

We see the following:

One interesting difference between lists and Series is that with Series, the index does not always need to correspond so closely with the position; that's just a default that can be overridden. We've already seen one way to do this (creating a Series from a dict). We can also build a Series with two aligned lists (one for the values and one for the index).

Now we see indexes are assigned based on the argument we passed for index (not the position):

When we do element-wise operations between two Series, Pandas lines up the data based on index, not position. As a concrete example, consider three Series:

Note: Y and Z are nearly the same (numbers 10, 20, and 30, in that order), except for the index. Let's see the difference between X+Y and X+Z:

For X+Y, Pandas adds the number at index 0 in X (100) with the value at index 0 in Y (10), such that the value in the output at index 0 is 110.

For X+Z, Pandas adds the number at index 0 in X (100) with the value at index 0 in Y (30), such that the value in the output at index 0 is 130. It doesn't matter that the first number in Z is 10, because Pandas does element-wise operations based on index, not position.

Boolean Indexing

We've seen this syntax before:

obj[X]

For a dictionary, X is a key, and for a list, X is an index. With a Series, X could be either of these things, or, interestingly, obj and X could both be a Series. In this last scenario, X must specifically be a Series of booleans. This type of lookup is often called "boolean indexing", or sometimes "fancy indexing."

As with element wise operations, fancy indexing aligns both Series:

Combining Element-Wise Operations with Selection

As we just saw, we can use a Boolean series (let's call it B) to select values from another Series (let's call it S).

A common pattern is to create B by performing operation on S, then using B to select from S. Let's try doing this to pull all the numbers greater than 5 from a Series.

Example 1: extract number > 5

Alternatively, you can combine all of the above steps.

Example 2: extract upper case letters

Let's try to pull out all the upper case strings from a series:

We have done this example in several steps to illustrate what is happening, but it could have been simplified. Recall that B is words == upper_words. Thus we could have done this without ever storing a Boolean series in B:

Let's simplify one step further (instead of using upper_words, let's paste the expression we used to compute it earlier):

Example 3: extract odd numbers

Let's try to pull out all the odd numbers from this Series:

nums % 2 well produce a Series of 1's (for odd numbers) and 0's (for even numbers). Thus nums % 2 == 1 produces a Boolean Series of True's (for odd numbers) and False's (for even numbers). Let's use that Boolean Series to pull out the odd numbers:

Example 4: using and and/or or

One might be able to perform operations like this in Pandas:

Series([True, False]) or Series([False, False])

Unfortunately, that doesn't work, because Python doesn't let modules like Pandas override the behavior of and and or. Instead, you must use & and | for these respectively.

Let's try to get the numbers between 10 and 20:

Cool, we got all the numbers between 10 and 20! Notice we needed extra parentheses, though. & and | are high precedence, so we need those to make the logical operators occur last.

How to get numbers < 12 or numbers > 33?

Pandas DataFrame

Pandas will often be used to deal with tabular data (much as in Excel).

In many tables, all the data in the same column is similar, so Pandas represents each column in a table as a Series object. A table is represented as a DataFrame, which is just a collection of named Series (one for each column).

We can use a dictionary of aligned Series objects to create a dictionary. For example:

Or, if we want, we can create a DataFrame table from a dictionary of lists, and Pandas will implicitly create the Series for each column for us:

Accessing DataFrame Values

There are a few things we might want to do:

  1. extract a column of data
  2. extract a row of data
  3. extract a single cell
  4. modify a single cell

Reading CSV Files

Most of the time, we'll let Pandas directly load a CSV file to a DataFrame (instead of creating a dictionary of lists ourselves). We can easily do this with pd.read_csv(path) (recall that we imported pandas as import pandas as pd):

Observe:

Let's pull out the movies from 2016 using this Boolean Series:

We see (among other things) that the average Runtime is 107.34 minutes.

Conclusion

Data comes in many different forms, but tabular data is especially common. The Pandas module helps us work with tabular data and integrates with ipython, making it fast and easy to compute simple statistics over columns within our dataset. In this lesson, we learned to do the following: