Python Review

In the following sections, we will repeatedly use Python scripts. In case you are less familiar with Python, here is a short tutorial on what you need to know. Also, please take a look here: Google’s Python Class- https://developers.google.com/edu/python

Introduction

Python is a general-purpose programming language that, combining with a few popular libraries (numpy, scipy, matplotlib), becomes a powerful environment for scientific computing.

!python --version
Python 3.7.12

Basics of Python

Python is a high-level, dynamically typed multiparadigm programming language. Python code is often said to be almost like pseudocode, since it allows you to express very powerful ideas in very few lines of code while being very readable.

Basic data types

Numbers

Integers and floats work as you would expect from other languages:

x = 3
print(x, type(x))
3 <class 'int'>
print(x + 1)  #addition
print(x - 1)  #subtraction
print(x * 2)  #multiplication
print(x ** 2) #exponentiation
4
2
6
9
x = 10; x += 1
print(x)
x = 10; x *= 2
print(x)
11
20
y = 2.5
print(y, y+1, y*2, y *2, type(y))
2.5 3.5 5.0 5.0 <class 'float'>

Booleans

Python implements all of the usual operators for Boolean logic, but uses English words rather than symbols:

t, f = True, False; print(type(t))
<class 'bool'>

Now we let’s look at the operations:

print(t and f) # Logical AND;
print(t or f)  # Logical OR;
print(not t)   # Logical NOT;
print(t != f)  # Logical XOR;
False
True
False
True

Strings

hello = 'hello'   # String literals can use single quotes
world = "world"   # or double quotes; it does not matter
print(hello, len(hello))
hello 5
hw = hello + '-' + world+'!'  # String concatenation
print(hw)
hello-world!
hw12 = '{} {} {}'.format(hello, world, 12)  # string formatting
print(hw12)
hello world 12

String objects have a bunch of useful methods; for example:

s = "hello"
print(s.capitalize())  # Capitalize a string
print(s.upper())       # Convert a string to uppercase; prints "HELLO"
print(s.rjust(7))      # Right-justify a string, padding with spaces
print(s.center(7))     # Center a string, padding with spaces
print(s.replace('l', '(ell)'))  # Replace all instances of one substring with another
print('  world '.strip())  # Strip leading and trailing whitespace
Hello
HELLO
  hello
 hello
he(ell)(ell)o
world

Lists

A list is the Python equivalent of an array, but is resizeable and can contain elements of different types:

xs = [3, 1, 2]   # Create a list
print(xs, xs[2])
print(xs[-1])     # Negative indices count from the end of the list; prints "2"
[3, 1, 2] 2
2
xs[2] = 'foo'    # Lists can contain elements of different types
print(xs)
[3, 1, 'foo']
xs.append('bar') # Add a new element to the end of the list
print(xs)
[3, 1, 'foo', 'bar']
x = xs.pop()     # Remove and return the last element of the list
print(x, xs)
bar [3, 1, 'foo']

Slicing

In addition to accessing list elements one at a time, Python provides concise syntax to access sublists; this is known as slicing:

nums = list(range(5))    # range is a built-in function that creates a list of integers
print(nums)         # Prints "[0, 1, 2, 3, 4]"
print(nums[2:4])    # Get a slice from index 2 to 4 (exclusive); prints "[2, 3]"
print(nums[2:])     # Get a slice from index 2 to the end; prints "[2, 3, 4]"
print(nums[:2])     # Get a slice from the start to index 2 (exclusive); prints "[0, 1]"
print(nums[:])      # Get a slice of the whole list; prints ["0, 1, 2, 3, 4]"
print(nums[:-1])    # Slice indices can be negative; prints ["0, 1, 2, 3]"
nums[2:4] = [8, 9] # Assign a new sublist to a slice
print(nums)         # Prints "[0, 1, 8, 9, 4]"
[0, 1, 2, 3, 4]
[2, 3]
[2, 3, 4]
[0, 1]
[0, 1, 2, 3, 4]
[0, 1, 2, 3]
[0, 1, 8, 9, 4]

Loops

You can loop over the elements of a list like this:

animals = ['cat', 'dog', 'monkey']
for animal in animals:
    print(animal)
cat
dog
monkey

If you want access to the index of each element within the body of a loop, use the built-in enumerate function:

animals = ['cat', 'dog', 'monkey']
for idx, animal in enumerate(animals):
    print('#{}: {}'.format(idx + 1, animal))
#1: cat
#2: dog
#3: monkey

List comprehensions:

When programming, frequently we want to transform one type of data into another. As a simple example, consider the following code that computes square numbers:

nums = [0, 1, 2, 3, 4]
squares = []
for x in nums:
    squares.append(x ** 2)
print(squares)
[0, 1, 4, 9, 16]

You can make this code simpler using a list comprehension:

nums = [0, 1, 2, 3, 4]
squares = [x ** 2 for x in nums]
print(squares)
[0, 1, 4, 9, 16]

List comprehensions can also contain conditions:

nums = [0, 1, 2, 3, 4]
even_squares = [x ** 2 for x in nums if x % 2 == 0]
print(even_squares)
[0, 4, 16]

Dictionaries

A dictionary stores (key, value) pairs

d = {'cat': 'cute', 'dog': 'furry'}  # Create a new dictionary with some data
print(d['cat'])       # Get an entry from a dictionary; prints "cute"
print('cat' in d)     # Check if a dictionary has a given key; prints "True"
cute
True
d['fish'] = 'wet'    # Set an entry in a dictionary
print(d['fish'])      # Prints "wet"
wet
print(d.get('monkey', 'N/A'))  # Get an element with a default; prints "N/A"
print(d.get('fish', 'N/A'))    # Get an element with a default; prints "wet"
N/A
wet
print(d)
{'cat': 'cute', 'dog': 'furry', 'fish': 'wet'}
del d['fish']        # Remove an element from a dictionary
print(d.get('fish', 'N/A')) # "fish" is no longer a key; prints "N/A"
N/A
print(d)
{'cat': 'cute', 'dog': 'furry'}

It is easy to iterate over the keys in a dictionary:

d = {'person': 2, 'cat': 4, 'spider': 8}
for animal, legs in d.items():
    print('A {} has {} legs'.format(animal, legs))
A person has 2 legs
A cat has 4 legs
A spider has 8 legs

Dictionary comprehensions: These are similar to list comprehensions, but allow you to easily construct dictionaries. For example:

nums = [0, 1, 2, 3, 4]
even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}
print(even_num_to_square)
{0: 0, 2: 4, 4: 16}

Sets

A set is an unordered collection of distinct elements. As a simple example, consider the following:

animals = {'cat', 'dog'}
print('cat' in animals)   # Check if an element is in a set; prints "True"
print('fish' in animals)  # prints "False"
print(animals)
True
False
{'dog', 'cat'}
animals.add('fish')      # Add an element to a set
print('fish' in animals)
print(len(animals))       # Number of elements in a set;
print(animals)
True
3
{'dog', 'cat', 'fish'}
animals.add('cat')       # Adding an element that is already in the set does nothing
print(len(animals))
animals.remove('cat')    # Remove an element from a set
print(len(animals))
print(animals)
3
2
{'dog', 'fish'}

Loops: Iterating over a set has the same syntax as iterating over a list; however since sets are unordered, you cannot make assumptions about the order in which you visit the elements of the set:

animals = {'cat', 'dog', 'fish'}
for idx, animal in enumerate(animals):
    print('#{}: {}'.format(idx + 1, animal))
#1: dog
#2: cat
#3: fish

Set comprehensions: Like lists and dictionaries, we can easily construct sets using set comprehensions:

from math import sqrt
print({int(sqrt(x)) for x in range(30)})
{0, 1, 2, 3, 4, 5}

Tuples

A tuple is an (immutable) ordered list of values. A tuple is in many ways similar to a list; one of the most important differences is that tuples can be used as keys in dictionaries and as elements of sets, while lists cannot. Here is a trivial example:

d = {(x, x + 1): x for x in range(7)}  # Create a dictionary with tuple keys
t = (5, 6)       # Create a tuple
print(type(t))
print(d)
print(d[t])
print(d[(1, 2)])
<class 'tuple'>
{(0, 1): 0, (1, 2): 1, (2, 3): 2, (3, 4): 3, (4, 5): 4, (5, 6): 5, (6, 7): 6}
5
1

Functions

Python functions are defined using the def keyword. For example:

def sign(x):
    if x > 0:
        return 'positive'
    elif x < 0:
        return 'negative'
    else:
        return 'zero'

for x in [-1, 0, 1]:
    print(sign(x))
negative
zero
positive

We will often define functions to take optional keyword arguments, like this:

def hello(name, loud=False):
    if loud:
        print('HELLO, {}'.format(name.upper()))
    else:
        print('Hello, {}!'.format(name))

hello('Bob')
hello('Fred', loud=True)
Hello, Bob!
HELLO, FRED

Classes

The syntax for defining classes in Python is straightforward:

class Greeter:

    # Constructor
    def __init__(self, name):
        self.name = name  # Create an *instance* variable

    # Instance method
    def greet(self, loud=False):
        if loud:
          print('HELLO, {}'.format(self.name.upper()))
        else:
          print('Hello, {}!'.format(self.name))

g = Greeter('Fred')  # Construct an instance of the Greeter class
print(g.name)
g.greet()            # Call an instance method; prints "Hello, Fred"
g.greet(loud=True)   # Call an instance method; prints "HELLO, FRED!"
Fred
Hello, Fred!
HELLO, FRED

Numpy

Numpy is the core library for scientific computing in Python. It provides a high-performance multidimensional array object, and tools for working with these arrays.

import numpy as np

Arrays

A numpy array is a grid of values, all of the same type, and is indexed by a tuple of nonnegative integers. The number of dimensions is the rank of the array; the shape of an array is a tuple of integers giving the size of the array along each dimension.

We can initialize numpy arrays from nested Python lists, and access elements using square brackets:

a = np.array([1, 2, 3])  # Create a rank 1 array
print(type(a), a.shape, a[0], a[1], a[2])
a[0] = 5                 # Change an element of the array
print(a)
<class 'numpy.ndarray'> (3,) 1 2 3
[5 2 3]
b = np.array([[1,2,3],[4,5,6]])   # Create a rank 2 array
print(b)
[[1 2 3]
 [4 5 6]]
print(b.shape)
print(b[0, 0], b[0, 1], b[1, 0])
(2, 3)
1 2 4

Numpy also provides many functions to create arrays:

a = np.zeros((2,2))  # Create an array of all zeros
print(a)
[[0. 0.]
 [0. 0.]]
b = np.ones((1,2))   # Create an array of all ones
print(b)
[[1. 1.]]
c = np.full((2,2), 7) # Create a constant array
print(c)
[[7 7]
 [7 7]]
d = np.eye(2)        # Create a 2x2 identity matrix
print(d)
[[1. 0.]
 [0. 1.]]
e = np.random.random((2,2)) # Create an array filled with random values between 0 and 1
print(e)
[[0.33426196 0.22871597]
 [0.80676993 0.17307073]]

Array indexing

Numpy offers several ways to index into arrays.

Slicing: Similar to Python lists, numpy arrays can be sliced. Since arrays may be multidimensional, you must specify a slice for each dimension of the array:

import numpy as np

a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
print(a)

# Use slicing to pull out the subarray consisting of the first 2 rows
# and columns 1 and 2; b is the following array of shape (2, 2):
# [[2 3]
#  [6 7]]
b = a[:2, 1:3]
print(b)
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
[[2 3]
 [6 7]]

A slice of an array is a view into the same data, so modifying it will modify the original array.

print(a[0, 1])
b[0, 0] = 77    # b[0, 0] is the same piece of data as a[0, 1]
print(a[0, 1])
2
77

Two ways of accessing the data in the middle row of the array. Mixing integer indexing with slices yields an array of lower rank, while using only slices yields an array of the same rank as the original array:

row_r1 = a[1, :]    # Rank 1 view of the second row of a
row_r2 = a[1:2, :]  # Rank 2 view of the second row of a
row_r3 = a[[1], :]  # Rank 2 view of the second row of a
print(row_r1, row_r1.shape)
print(row_r2, row_r2.shape)
print(row_r3, row_r3.shape)
[5 6 7 8] (4,)
[[5 6 7 8]] (1, 4)
[[5 6 7 8]] (1, 4)
# We can make the same distinction when accessing columns of an array:
col_r1 = a[:, 1]
col_r2 = a[:, 1:2]
print(col_r1, col_r1.shape)
print()
print(col_r2, col_r2.shape)
[77  6 10] (3,)

[[77]
 [ 6]
 [10]] (3, 1)

Integer array indexing: When you index into numpy arrays using slicing, the resulting array view will always be a subarray of the original array. In contrast, integer array indexing allows you to construct arbitrary arrays using the data from another array. Here is an example:

a = np.array([[1,2], [3, 4], [5, 6]])

# An example of integer array indexing.
# The returned array will have shape (3,) and
print(a[[0, 1, 2], [0, 1, 0]])

# The above example of integer array indexing is equivalent to this:
print(np.array([a[0, 0], a[1, 1], a[2, 0]]))
[1 4 5]
[1 4 5]
# When using integer array indexing, you can reuse the same
# element from the source array:
print(a[[0, 0], [1, 1]])

# Equivalent to the previous integer array indexing example
print(np.array([a[0, 1], a[0, 1]]))
[2 2]
[2 2]

One useful trick with integer array indexing is selecting or mutating one element from each row of a matrix:

# Create a new array from which we will select elements
a = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
print(a)
[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]]
# Create an array of indices
b = np.array([0, 2, 0, 1])

# Select one element from each row of a using the indices in b
print(a[np.arange(4), b])  # Prints "[ 1  6  7 11]"
[ 1  6  7 11]
# Mutate one element from each row of a using the indices in b
a[np.arange(4), b] += 10
print(a)
[[11  2  3]
 [ 4  5 16]
 [17  8  9]
 [10 21 12]]

Boolean array indexing: Boolean array indexing lets you pick out arbitrary elements of an array. Frequently this type of indexing is used to select the elements of an array that satisfy some condition. Here is an example:

import numpy as np

a = np.array([[1,2], [3, 4], [5, 6]])

bool_idx = (a > 2)  # Find the elements of a that are bigger than 2;
                    # this returns a numpy array of Booleans of the same
                    # shape as a, where each slot of bool_idx tells
                    # whether that element of a is > 2.

print(bool_idx)
[[False False]
 [ True  True]
 [ True  True]]
# We use boolean array indexing to construct a rank 1 array
# consisting of the elements of a corresponding to the True values
# of bool_idx
print(a[bool_idx])

# We can do all of the above in a single concise statement:
print(a[a > 2])
[3 4 5 6]
[3 4 5 6]

For brevity we have left out a lot of details about numpy array indexing; if you want to know more you should read the documentation.

Datatypes

Every numpy array is a grid of elements of the same type. Numpy provides a large set of numeric datatypes that you can use to construct arrays. Numpy tries to guess a datatype when you create an array, but functions that construct arrays usually also include an optional argument to explicitly specify the datatype. Here is an example:

x = np.array([1, 2])  # Let numpy choose the datatype
y = np.array([1.0, 2.0])  # Let numpy choose the datatype
z = np.array([1, 2], dtype=np.int64)  # Force a particular datatype

print(x.dtype, y.dtype, z.dtype)
int64 float64 int64

Array math

Basic mathematical functions operate elementwise on arrays, and are available both as operator overloads and as functions in the numpy module:

x = np.array([[1,2],[3,4]], dtype=np.float64)
y = np.array([[5,6],[7,8]], dtype=np.float64)

# Elementwise sum; both produce the array
print(x + y)
print(np.add(x, y))
[[ 6.  8.]
 [10. 12.]]
[[ 6.  8.]
 [10. 12.]]
# Elementwise difference; both produce the array
print(x - y)
print(np.subtract(x, y))
[[-4. -4.]
 [-4. -4.]]
[[-4. -4.]
 [-4. -4.]]
# Elementwise product; both produce the array
print(x * y)
print(np.multiply(x, y))
[[ 5. 12.]
 [21. 32.]]
[[ 5. 12.]
 [21. 32.]]
# Elementwise division; both produce the array
# [[ 0.2         0.33333333]
#  [ 0.42857143  0.5       ]]
print(x / y)
print(np.divide(x, y))
[[0.2        0.33333333]
 [0.42857143 0.5       ]]
[[0.2        0.33333333]
 [0.42857143 0.5       ]]
# Elementwise square root; produces the array
# [[ 1.          1.41421356]
#  [ 1.73205081  2.        ]]
print(np.sqrt(x))
[[1.         1.41421356]
 [1.73205081 2.        ]]

The dot function is used to compute inner products of vectors, to multiply a vector by a matrix, and to multiply matrices. dot is available both as a function in the numpy module and as an instance method of array objects:

x = np.array([[1,2],[3,4]])
y = np.array([[5,6],[7,8]])

v = np.array([9,10])
w = np.array([11, 12])

# Inner product of vectors; both produce 219
print(v.dot(w))
print(np.dot(v, w))
219
219

You can also use the @ operator which is equivalent to numpy’s dot operator.

print(v @ w)
219
# Matrix / vector product; both produce the rank 1 array [29 67]
print(x.dot(v))
print(np.dot(x, v))
print(x @ v)
[29 67]
[29 67]
[29 67]
# Matrix / matrix product; both produce the rank 2 array
# [[19 22]
#  [43 50]]
print(x.dot(y))
print(np.dot(x, y))
print(x @ y)
[[19 22]
 [43 50]]
[[19 22]
 [43 50]]
[[19 22]
 [43 50]]

Numpy provides many useful functions for performing computations on arrays; one of the most useful is sum:

x = np.array([[1,2],[3,4]])

print(np.sum(x))  # Compute sum of all elements; prints "10"
print(np.sum(x, axis=0))  # Compute sum of each column; prints "[4 6]"
print(np.sum(x, axis=1))  # Compute sum of each row; prints "[3 7]"
10
[4 6]
[3 7]

Apart from computing mathematical functions using arrays, we frequently need to reshape or otherwise manipulate data in arrays. The simplest example of this type of operation is transposing a matrix; to transpose a matrix, simply use the T attribute of an array object:

print(x)
print(x.T)
[[1 2]
 [3 4]]
[[1 3]
 [2 4]]
v = np.array([[1,2,3]])
print(v )
print(v.T)
[[1 2 3]]
[[1]
 [2]
 [3]]

Broadcasting

Broadcasting is a powerful mechanism that allows numpy to work with arrays of different shapes when performing arithmetic operations. Frequently we have a smaller array and a larger array, and we want to use the smaller array multiple times to perform some operation on the larger array.

For example, suppose that we want to add a constant vector to each row of a matrix. We could do it like this:

# We will add the vector v to each row of the matrix x,
# storing the result in the matrix y
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = np.zeros_like(x)   # an array of zeros with the same shape and type as x
print(y)
print(x.shape,v.shape,y.shape)

# Add the vector v to each row of the matrix x with an explicit loop
for i in range(4):
    y[i, :] = x[i, :] + v

print(y)
[[0 0 0]
 [0 0 0]
 [0 0 0]
 [0 0 0]]
(4, 3) (3,) (4, 3)
[[ 2  2  4]
 [ 5  5  7]
 [ 8  8 10]
 [11 11 13]]

This works; however when the matrix x is very large, computing an explicit loop in Python could be slow. Note that adding the vector v to each row of the matrix x is equivalent to forming a matrix vv by stacking multiple copies of v vertically, then performing elementwise summation of x and vv. We could implement this approach like this:

print(v)
vv = np.tile(v, (4, 1))  # Stack 4 copies of v on top of each other
print(vv)                # Prints "[[1 0 1]
                         #          [1 0 1]
                         #          [1 0 1]
                         #          [1 0 1]]"
[1 0 1]
[[1 0 1]
 [1 0 1]
 [1 0 1]
 [1 0 1]]
y = x + vv  # Add x and vv elementwise
print(y)
[[ 2  2  4]
 [ 5  5  7]
 [ 8  8 10]
 [11 11 13]]

Numpy broadcasting allows us to perform this computation without actually creating multiple copies of v. Consider this version, using broadcasting:

import numpy as np

# We will add the vector v to each row of the matrix x,
# storing the result in the matrix y
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = x + v  # Add v to each row of x using broadcasting
print(y)
[[ 2  2  4]
 [ 5  5  7]
 [ 8  8 10]
 [11 11 13]]

The line y = x + v works even though x has shape (4, 3) and v has shape (3,) due to broadcasting; this line works as if v actually had shape (4, 3), where each row was a copy of v, and the sum was performed elementwise.

Broadcasting two arrays together follows these rules:

  1. If the arrays do not have the same rank, prepend the shape of the lower rank array with 1s until both shapes have the same length.

  2. The two arrays are said to be compatible in a dimension if they have the same size in the dimension, or if one of the arrays has size 1 in that dimension.

  3. The arrays can be broadcast together if they are compatible in all dimensions.

  4. After broadcasting, each array behaves as if it had shape equal to the elementwise maximum of shapes of the two input arrays.

  5. In any dimension where one array had size 1 and the other array had size greater than 1, the first array behaves as if it were copied along that dimension

Here are some applications of broadcasting:

# Compute outer product of vectors
v = np.array([1,2,3])  # v has shape (3,)
w = np.array([4,5])    # w has shape (2,)
# To compute an outer product, we first reshape v to be a column
# vector of shape (3, 1); we can then broadcast it against w to yield
# an output of shape (3, 2), which is the outer product of v and w:

print(np.reshape(v, (3, 1)) * w)
print(v.shape, w.shape)
[[ 4  5]
 [ 8 10]
 [12 15]]
(3,) (2,)
# Add a vector to each row of a matrix
x = np.array([[1,2,3], [4,5,6]])
# x has shape (2, 3) and v has shape (3,) so they broadcast to (2, 3),
# giving the following matrix:

print(x + v)
[[2 4 6]
 [5 7 9]]
# Add a vector to each column of a matrix
# x has shape (2, 3) and w has shape (2,).
# If we transpose x then it has shape (3, 2) and can be broadcast
# against w to yield a result of shape (3, 2); transposing this result
# yields the final result of shape (2, 3) which is the matrix x with
# the vector w added to each column. Gives the following matrix:

print((x.T + w).T)
[[ 5  6  7]
 [ 9 10 11]]
# Another solution is to reshape w to be a row vector of shape (2, 1);
# we can then broadcast it directly against x to produce the same
# output.
print(x + np.reshape(w, (2, 1)))
[[ 5  6  7]
 [ 9 10 11]]
# Multiply a matrix by a constant:
# x has shape (2, 3). Numpy treats scalars as arrays of shape ();
# these can be broadcast together to shape (2, 3), producing the
# following array:
print(x * 2)
[[ 2  4  6]
 [ 8 10 12]]

Broadcasting typically makes your code more concise and faster, so you should strive to use it where possible.

Pandas

Pandas is a software library in Python for data manipulation and analysis. It offers data structures and operations for manipulating numerical tables and time series. The main data structure is the DataFrame, which is an in-memory 2D table similar to a spreadsheet, with column names and row labels.

import pandas as pd

Series objects

A Series object is 1D array, similar to a column in a spreadsheet, while a DataFrame objects is a 2D table with column names and row labels.

s = pd.Series([1,2,3,4]); s
0    1
1    2
2    3
3    4
dtype: int64

Series objects can be passed as parameters to NumPy functions

np.log(s)
0    0.000000
1    0.693147
2    1.098612
3    1.386294
dtype: float64
s = s + s + [1,2,3,4] # elementwise addition with a list
s
0     3
1     6
2     9
3    12
dtype: int64
s = s + 1 #Broadcasting
s
0     4
1     7
2    10
3    13
dtype: int64
s >=10
0    False
1    False
2     True
3     True
dtype: bool

Index labels

Each item in a Series object has a unique identifier called index label. By default, it is simply the rank of the item in the Series (starting at 0) but you can also set the index labels manually

s2 = pd.Series([1, 2, 3, 4], index=["a", "b", "c", "d"])
s2
a    1
b    2
c    3
d    4
dtype: int64

You can then use the Series just like a dict object

s2['b']
2

access items by integer location

s2[1]
2
s2.loc['b'] #accessing by label
2
s2.iloc[1] #accessing by integer location
2

Slicing a Series

s2.iloc[1:3]
b    2
c    3
dtype: int64
s2.iloc[2:]
c    3
d    4
dtype: int64

Initializing from a dict

Create a Series object from a dict, keys are used as index labels

d = {"b": 1, "a": 2, "e": 3, "d": 4}
s3 = pd.Series(d)
s3
b    1
a    2
e    3
d    4
dtype: int64
s4 = pd.Series(d, index = ["c", "a"])
s4
c    NaN
a    2.0
dtype: float64
s5 = pd.Series(10, ["a", "b", "c"], name="series")
s5
a    10
b    10
c    10
Name: series, dtype: int64

Automatic alignment

When an operation involves multiple Series objects, pandas automatically aligns items by matching index labels.

print(s2.keys())
print(s3.keys())

s2 + s3
Index(['a', 'b', 'c', 'd'], dtype='object')
Index(['b', 'a', 'e', 'd'], dtype='object')
a    3.0
b    3.0
c    NaN
d    8.0
e    NaN
dtype: float64

The resulting Series contains the union of index labels from s2 and s3. But, missing index labels get the value of NaN

DataFrame objects

DataFrame object represents a spreadsheet, with cell values, column names and row index labels.

d = {
    "feature1": pd.Series([1,2,3], index=["a", "b", "c"]),
    "feature2": pd.Series([4,5,6], index=["b", "a", "c"]),
    "feature3": pd.Series([7,8],  index=["c", "b"]),
    "feature4": pd.Series([9,10], index=["a", "b"]),
}
df = pd.DataFrame(d)
df
feature1 feature2 feature3 feature4
a 1 5 NaN 9.0
b 2 4 8.0 10.0
c 3 6 7.0 NaN

You can access columns pretty much as you would expect. They are returned as Series objects:

df["feature3"] #accessing a column
a    NaN
b    8.0
c    7.0
Name: feature3, dtype: float64
df[["feature1", "feature3"]] #accessing ,multiple columns
feature1 feature3
a 1 NaN
b 2 8.0
c 3 7.0
df
feature1 feature2 feature3 feature4
a 1 5 NaN 9.0
b 2 4 8.0 10.0
c 3 6 7.0 NaN

Constructing a new DataFrame from an existing DataFrame

df2 = pd.DataFrame(
        df,
        columns=["feature1", "feature2", "feature3"],
        index=["b", "a", "d"]
     )
df2
feature1 feature2 feature3
b 2.0 4.0 8.0
a 1.0 5.0 NaN
d NaN NaN NaN

Creating a DataFrame from a list of lists

lol = [
            [11, 1,      "a",   np.nan],
            [12, 3,      "b",       14],
            [13, np.nan, np.nan,    15]
         ]
df3 = pd.DataFrame(
        lol,
        columns=["feature1", "feature2", "feature3", "feature4"],
        index=["a", "b", "c"]
     )
df3
feature1 feature2 feature3 feature4
a 11 1.0 a NaN
b 12 3.0 b 14.0
c 13 NaN NaN 15.0

Creating a DataFrame with a dictionary of dictionaries

df5 = pd.DataFrame({
    "feature1": {"a": 15, "b": 1984, "c": 4},
    "feature2": {"a": "sentence", "b": "word"},
    "feature3": {"a": 1, "b": 83, "c": 4},
    "feature4": {"c": 2, "d": 0}
})
df5
feature1 feature2 feature3 feature4
a 15.0 sentence 1.0 NaN
b 1984.0 word 83.0 NaN
c 4.0 NaN 4.0 2.0
d NaN NaN NaN 0.0

Multi-indexing

If all columns/rows are tuples of the same size, then they are understood as a multi-index

df5 = pd.DataFrame(
  {
    ("features12", "feature1"):
        {("rows_ab","a"): 444, ("rows_ab","b"): 444, ("rows_c","c"): 666},
    ("features12", "feature2"):
        {("rows_ab","a"): 111, ("rows_ab","b"): 222},
    ("features34", "feature3"):
        {("rows_ab","a"): 555, ("rows_ab","b"): 333, ("rows_c","c"): 777},
    ("features34", "feature4"):
        {("rows_ab", "a"):333, ("rows_ab","b"): 999, ("rows_c","c"): 888}
  }
)
df5
features12 features34
feature1 feature2 feature3 feature4
rows_ab a 444 111.0 555 333
b 444 222.0 333 999
rows_c c 666 NaN 777 888
df5['features12']
feature1 feature2
rows_ab a 444 111.0
b 444 222.0
rows_c c 666 NaN
df5['features12','feature1']
rows_ab  a    444
         b    444
rows_c   c    666
Name: (features12, feature1), dtype: int64
df5['features12','feature1']['rows_c']
c    666
Name: (features12, feature1), dtype: int64
df5.loc['rows_c']
features12 features34
feature1 feature2 feature3 feature4
c 666 NaN 777 888
df5.loc['rows_ab','features12']
feature1 feature2
a 444 111.0
b 444 222.0

Dropping a level

df5.columns = df5.columns.droplevel(level = 0);
df5
feature1 feature2 feature3 feature4
rows_ab a 444 111.0 555 333
b 444 222.0 333 999
rows_c c 666 NaN 777 888

Transposing

swaping columns and indices

df6 = df5.T
df6
rows_ab rows_c
a b c
feature1 444.0 444.0 666.0
feature2 111.0 222.0 NaN
feature3 555.0 333.0 777.0
feature4 333.0 999.0 888.0

Stacking and unstacking levels

expanding the lowest column level as the lowest index

df7 = df6.stack()
df7
rows_ab rows_c
feature1 a 444.0 NaN
b 444.0 NaN
c NaN 666.0
feature2 a 111.0 NaN
b 222.0 NaN
feature3 a 555.0 NaN
b 333.0 NaN
c NaN 777.0
feature4 a 333.0 NaN
b 999.0 NaN
c NaN 888.0
df8 = df7.unstack()
df8
rows_ab rows_c
a b c a b c
feature1 444.0 444.0 NaN NaN NaN 666.0
feature2 111.0 222.0 NaN NaN NaN NaN
feature3 555.0 333.0 NaN NaN NaN 777.0
feature4 333.0 999.0 NaN NaN NaN 888.0

If we call unstack again, we end up with a Series object

df9 = df8.unstack()
df9
rows_ab  a  feature1    444.0
            feature2    111.0
            feature3    555.0
            feature4    333.0
         b  feature1    444.0
            feature2    222.0
            feature3    333.0
            feature4    999.0
         c  feature1      NaN
            feature2      NaN
            feature3      NaN
            feature4      NaN
rows_c   a  feature1      NaN
            feature2      NaN
            feature3      NaN
            feature4      NaN
         b  feature1      NaN
            feature2      NaN
            feature3      NaN
            feature4      NaN
         c  feature1    666.0
            feature2      NaN
            feature3    777.0
            feature4    888.0
dtype: float64

Accessing rows

df
feature1 feature2 feature3 feature4
a 1 5 NaN 9.0
b 2 4 8.0 10.0
c 3 6 7.0 NaN
df.loc["c"] #access the c row
feature1    3.0
feature2    6.0
feature3    7.0
feature4    NaN
Name: c, dtype: float64
df.iloc[2] #access the 2nd column
feature1    3.0
feature2    6.0
feature3    7.0
feature4    NaN
Name: c, dtype: float64

slice of rows

df.iloc[1:3]
feature1 feature2 feature3 feature4
b 2 4 8.0 10.0
c 3 6 7.0 NaN

slice rows using boolean array

df[np.array([True, False, True])]
feature1 feature2 feature3 feature4
a 1 5 NaN 9.0
c 3 6 7.0 NaN

This is most useful when combined with boolean expressions:

df[df["feature2"] <=5]
feature1 feature2 feature3 feature4
a 1 5 NaN 9.0
b 2 4 8.0 10.0

Adding and removing columns

df
feature1 feature2 feature3 feature4
a 1 5 NaN 9.0
b 2 4 8.0 10.0
c 3 6 7.0 NaN
df['feature5'] = 5 - df['feature2'] #adding a column
df['feature6'] = df['feature3'] > 5
df
feature1 feature2 feature3 feature4 feature5 feature6
a 1 5 NaN 9.0 0 False
b 2 4 8.0 10.0 1 True
c 3 6 7.0 NaN -1 True
del df['feature6']
df
feature1 feature2 feature3 feature4 feature5
a 1 5 NaN 9.0 0
b 2 4 8.0 10.0 1
c 3 6 7.0 NaN -1
df["feature6"] = pd.Series({"feature2": 1, "feature4": 51, "feature1":1})
df
feature1 feature2 feature3 feature4 feature5 feature6
a 1 5 NaN 9.0 0 NaN
b 2 4 8.0 10.0 1 NaN
c 3 6 7.0 NaN -1 NaN
df.insert(1, "feature1b", [0,1,2])
df
feature1 feature1b feature2 feature3 feature4 feature5 feature6
a 1 0 5 NaN 9.0 0 NaN
b 2 1 4 8.0 10.0 1 NaN
c 3 2 6 7.0 NaN -1 NaN

Assigning new columns

create a new DataFrame with new columns

df
feature1 feature1b feature2 feature3 feature4 feature5 feature6
a 1 0 5 NaN 9.0 0 NaN
b 2 1 4 8.0 10.0 1 NaN
c 3 2 6 7.0 NaN -1 NaN
df10 = df.assign(feature0 = df["feature1"] * df["feature2"] )
df10.assign(feature1 = df10["feature1"] +1)
df10
feature1 feature1b feature2 feature3 feature4 feature5 feature6 feature0
a 1 0 5 NaN 9.0 0 NaN 5
b 2 1 4 8.0 10.0 1 NaN 8
c 3 2 6 7.0 NaN -1 NaN 18

Evaluating an expression

df = df[['feature1','feature2','feature3','feature4']]
df.eval("feature1 + feature2 ** 2")
a    26
b    18
c    39
dtype: int64
df
feature1 feature2 feature3 feature4
a 1 5 NaN 9.0
b 2 4 8.0 10.0
c 3 6 7.0 NaN

use inplace=True to modify the original DataFrame

df.eval("feature3 = feature1 + feature2 ** 2", inplace=True)
df
feature1 feature2 feature3 feature4
a 1 5 26 9.0
b 2 4 18 10.0
c 3 6 39 NaN

use a local or global variable in an expression by prefixing it with @

threshold = 30
df.eval("feature3 = feature1 + feature2 ** 2 > @threshold", inplace=True)
df
feature1 feature2 feature3 feature4
a 1 5 False 9.0
b 2 4 False 10.0
c 3 6 True NaN

Querying a DataFrame

The query method lets you filter a DataFrame

df.query("feature1 > 2 and feature2 == 6")
feature1 feature2 feature3 feature4
c 3 6 True NaN

Sorting a DataFrame

df
feature1 feature2 feature3 feature4
a 1 5 False 9.0
b 2 4 False 10.0
c 3 6 True NaN
df.sort_index(ascending=False)
feature1 feature2 feature3 feature4
c 3 6 True NaN
b 2 4 False 10.0
a 1 5 False 9.0
df.sort_index(axis=1, inplace=True)
df
feature1 feature2 feature3 feature4
a 1 5 False 9.0
b 2 4 False 10.0
c 3 6 True NaN
df.sort_values(by="feature2", inplace=True)
df
/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  """Entry point for launching an IPython kernel.
feature1 feature2 feature3 feature4
b 2 4 False 10.0
a 1 5 False 9.0
c 3 6 True NaN

Operations on DataFrame

a = np.array([[1,2,3],[4,5,6],[7,8,9]])
df = pd.DataFrame(a, columns=["q", "w", "e"], index=["a","b","c"])
df
q w e
a 1 2 3
b 4 5 6
c 7 8 9
np.sqrt(df)
q w e
a 1.000000 1.414214 1.732051
b 2.000000 2.236068 2.449490
c 2.645751 2.828427 3.000000
df + 1 #broadcasting
q w e
a 2 3 4
b 5 6 7
c 8 9 10
df >= 5
q w e
a False False False
b False True True
c True True True
df.mean(), df.std(), df.max(), df.sum()
(q    4.0
 w    5.0
 e    6.0
 dtype: float64, q    3.0
 w    3.0
 e    3.0
 dtype: float64, q    7
 w    8
 e    9
 dtype: int64, q    12
 w    15
 e    18
 dtype: int64)

The All method checks whether all values are True or not

df
q w e
a 1 2 3
b 4 5 6
c 7 8 9
(df > 2).all()
q    False
w    False
e     True
dtype: bool
(df > 2).all(axis = 0) #executed vertically (on each column)
q    False
w    False
e     True
dtype: bool
(df > 2).all(axis = 1) #execute the horizontally (on each row).
a    False
b     True
c     True
dtype: bool
(df == 8).any(axis = 1)
a    False
b    False
c     True
dtype: bool
df - df.mean()
q w e
a -3.0 -3.0 -3.0
b 0.0 0.0 0.0
c 3.0 3.0 3.0
df - df.values.mean() # subtracts the global mean elementwise
q w e
a -4.0 -3.0 -2.0
b -1.0 0.0 1.0
c 2.0 3.0 4.0

Handling missing data

Pandas offers a few tools to handle missing data (NaN).

df10
feature1 feature1b feature2 feature3 feature4 feature5 feature6 feature0
a 1 0 5 NaN 9.0 0 NaN 5
b 2 1 4 8.0 10.0 1 NaN 8
c 3 2 6 7.0 NaN -1 NaN 18
df11 = df10.fillna(0)
df11
feature1 feature1b feature2 feature3 feature4 feature5 feature6 feature0
a 1 0 5 0.0 9.0 0 0.0 5
b 2 1 4 8.0 10.0 1 0.0 8
c 3 2 6 7.0 0.0 -1 0.0 18
df11.loc["d"] = np.nan
df11.fillna(0,inplace=True)
df11
#grades + fixed_bonus_points
feature1 feature1b feature2 feature3 feature4 feature5 feature6 feature0
a 1.0 0.0 5.0 0.0 9.0 0.0 0.0 5.0
b 2.0 1.0 4.0 8.0 10.0 1.0 0.0 8.0
c 3.0 2.0 6.0 7.0 0.0 -1.0 0.0 18.0
d 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0

Aggregating with groupby

Similar to the SQL language, pandas allows grouping your data into groups to run calculations over each group.

df5 = pd.DataFrame({
    "feature1": {"a": 3, "b": 11, "c": 14, 'd':4},
    "feature2": {"a": 2, "b": 2, "c": 4, 'd':4},
    "feature3": {"a": 32, "b": 4, "c": 3, 'd':35},
    "feature4": {"a": 5, "b": 11, "c": 2, 'd':13}
})
df5
feature1 feature2 feature3 feature4
a 3 2 32 5
b 11 2 4 11
c 14 4 3 2
d 4 4 35 13
df5.groupby("feature2").mean()
feature1 feature3 feature4
feature2
2 7.0 18.0 8.0
4 9.0 19.0 7.5

Pivot tables

pivot tables allows for quick data summarization

df9 = df8.stack().reset_index()
df9
level_0 level_1 rows_ab rows_c
0 feature1 a 444.0 NaN
1 feature1 b 444.0 NaN
2 feature1 c NaN 666.0
3 feature2 a 111.0 NaN
4 feature2 b 222.0 NaN
5 feature3 a 555.0 NaN
6 feature3 b 333.0 NaN
7 feature3 c NaN 777.0
8 feature4 a 333.0 NaN
9 feature4 b 999.0 NaN
10 feature4 c NaN 888.0
pd.pivot_table(df9, index="level_0")
rows_ab rows_c
level_0
feature1 444.0 666.0
feature2 166.5 NaN
feature3 444.0 777.0
feature4 666.0 888.0
pd.pivot_table(df9, index="level_0", values=["rows_ab"], aggfunc=np.max)
rows_ab
level_0
feature1 444.0
feature2 222.0
feature3 555.0
feature4 999.0

functions

When dealing with large DataFrames, it is useful to get a quick overview of its content. Pandas offers a few functions for this. First, let’s create a large DataFrame with a mix of numeric values, missing values and text values. Notice how Jupyter displays only the corners of the DataFrame:

df = np.fromfunction(lambda x,y: (x+y)%7*11, (10000, 26))
large_df = pd.DataFrame(df, columns=list("ABCDEFGHIJKLMNOPQRSTUVWXYZ"))
large_df.head(5)
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
0 0.0 11.0 22.0 33.0 44.0 55.0 66.0 0.0 11.0 22.0 33.0 44.0 55.0 66.0 0.0 11.0 22.0 33.0 44.0 55.0 66.0 0.0 11.0 22.0 33.0 44.0
1 11.0 22.0 33.0 44.0 55.0 66.0 0.0 11.0 22.0 33.0 44.0 55.0 66.0 0.0 11.0 22.0 33.0 44.0 55.0 66.0 0.0 11.0 22.0 33.0 44.0 55.0
2 22.0 33.0 44.0 55.0 66.0 0.0 11.0 22.0 33.0 44.0 55.0 66.0 0.0 11.0 22.0 33.0 44.0 55.0 66.0 0.0 11.0 22.0 33.0 44.0 55.0 66.0
3 33.0 44.0 55.0 66.0 0.0 11.0 22.0 33.0 44.0 55.0 66.0 0.0 11.0 22.0 33.0 44.0 55.0 66.0 0.0 11.0 22.0 33.0 44.0 55.0 66.0 0.0
4 44.0 55.0 66.0 0.0 11.0 22.0 33.0 44.0 55.0 66.0 0.0 11.0 22.0 33.0 44.0 55.0 66.0 0.0 11.0 22.0 33.0 44.0 55.0 66.0 0.0 11.0
large_df[large_df % 3 == 0] = np.nan
large_df.insert(3,"feature1", "xxx")
large_df.head(5)
A B C feature1 D E F G H I J K L M N O P Q R S T U V W X Y Z
0 NaN 11.0 22.0 xxx NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0
1 11.0 22.0 NaN xxx 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0
2 22.0 NaN 44.0 xxx 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN
3 NaN 44.0 55.0 xxx NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN
4 44.0 55.0 NaN xxx NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0
large_df.tail(4)
A B C feature1 D E F G H I J K L M N O P Q R S T U V W X Y Z
9996 NaN 11.0 22.0 xxx NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0
9997 11.0 22.0 NaN xxx 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0
9998 22.0 NaN 44.0 xxx 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN
9999 NaN 44.0 55.0 xxx NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN
large_df.describe()
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
count 5714.000000 5715.000000 5715.000000 5714.000000 5714.000000 5714.000000 5714.000000 5714.000000 5715.000000 5715.000000 5714.000000 5714.000000 5714.000000 5714.000000 5714.000000 5715.000000 5715.000000 5714.000000 5714.000000 5714.000000 5714.000000 5714.000000 5715.000000 5715.000000 5714.000000 5714.000000
mean 32.994225 32.996150 33.003850 33.005775 33.005775 33.000000 32.994225 32.994225 32.996150 33.003850 33.005775 33.005775 33.000000 32.994225 32.994225 32.996150 33.003850 33.005775 33.005775 33.000000 32.994225 32.994225 32.996150 33.003850 33.005775 33.005775
std 17.394048 17.393135 17.393135 17.394048 17.394048 17.395876 17.394048 17.394048 17.393135 17.393135 17.394048 17.394048 17.395876 17.394048 17.394048 17.393135 17.393135 17.394048 17.394048 17.395876 17.394048 17.394048 17.393135 17.393135 17.394048 17.394048
min 11.000000 11.000000 11.000000 11.000000 11.000000 11.000000 11.000000 11.000000 11.000000 11.000000 11.000000 11.000000 11.000000 11.000000 11.000000 11.000000 11.000000 11.000000 11.000000 11.000000 11.000000 11.000000 11.000000 11.000000 11.000000 11.000000
25% 13.750000 16.500000 22.000000 22.000000 22.000000 13.750000 13.750000 13.750000 16.500000 22.000000 22.000000 22.000000 13.750000 13.750000 13.750000 16.500000 22.000000 22.000000 22.000000 13.750000 13.750000 13.750000 16.500000 22.000000 22.000000 22.000000
50% 22.000000 22.000000 44.000000 44.000000 44.000000 33.000000 22.000000 22.000000 22.000000 44.000000 44.000000 44.000000 33.000000 22.000000 22.000000 22.000000 44.000000 44.000000 44.000000 33.000000 22.000000 22.000000 22.000000 44.000000 44.000000 44.000000
75% 44.000000 44.000000 49.500000 52.250000 52.250000 52.250000 44.000000 44.000000 44.000000 49.500000 52.250000 52.250000 52.250000 44.000000 44.000000 44.000000 49.500000 52.250000 52.250000 52.250000 44.000000 44.000000 44.000000 49.500000 52.250000 52.250000
max 55.000000 55.000000 55.000000 55.000000 55.000000 55.000000 55.000000 55.000000 55.000000 55.000000 55.000000 55.000000 55.000000 55.000000 55.000000 55.000000 55.000000 55.000000 55.000000 55.000000 55.000000 55.000000 55.000000 55.000000 55.000000 55.000000

saving and loading

large_df
A B C feature1 D E F G H I J K L M N O P Q R S T U V W X Y Z
0 NaN 11.0 22.0 xxx NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0
1 11.0 22.0 NaN xxx 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0
2 22.0 NaN 44.0 xxx 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN
3 NaN 44.0 55.0 xxx NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN
4 44.0 55.0 NaN xxx NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
9995 NaN NaN 11.0 xxx 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN
9996 NaN 11.0 22.0 xxx NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0
9997 11.0 22.0 NaN xxx 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0
9998 22.0 NaN 44.0 xxx 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN
9999 NaN 44.0 55.0 xxx NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN 11.0 22.0 NaN 44.0 55.0 NaN NaN

10000 rows × 27 columns

save and load

large_df.to_csv("my_df.csv")
large_df.to_csv("my_df.xlsx")
df0 = pd.read_csv("my_df.csv", index_col=0)

combining DataFrames

pandas has the ability to perform SQL-like joins: inner joins, left/right outer joins and full joins

city_loc = pd.DataFrame(
    [
        ["CA", "San Francisco", 37.781334, -122.416728],
        ["NY", "New York", 40.705649, -74.008344],
        ["FL", "Miami", 25.791100, -80.320733],
        ["OH", "Cleveland", 41.473508, -81.739791],
        ["UT", "Salt Lake City", 40.755851, -111.896657]
    ], columns=["state", "city", "lat", "lon"])
city_loc
state city lat lon
0 CA San Francisco 37.781334 -122.416728
1 NY New York 40.705649 -74.008344
2 FL Miami 25.791100 -80.320733
3 OH Cleveland 41.473508 -81.739791
4 UT Salt Lake City 40.755851 -111.896657
city_pop = pd.DataFrame(
    [
        [808976, "San Francisco", "California"],
        [8363710, "New York", "New York"],
        [413201, "Miami", "Florida"],
        [2242193, "Houston", "Texas"]
    ], index=[3,4,5,6], columns=["population", "city", "state"])
city_pop
population city state
3 808976 San Francisco California
4 8363710 New York New York
5 413201 Miami Florida
6 2242193 Houston Texas
pd.merge(left=city_loc, right=city_pop, on="city")
state_x city lat lon population state_y
0 CA San Francisco 37.781334 -122.416728 808976 California
1 NY New York 40.705649 -74.008344 8363710 New York
2 FL Miami 25.791100 -80.320733 413201 Florida

Note that both DataFrames have a column named state, so in the result they got renamed to state_x and state_y.

Also, note that Cleveland, Salt Lake City and Houston were dropped because they don’t exist in both DataFrames. This is the equivalent of a SQL INNER JOIN. If you want a FULL OUTER JOIN, where no city gets dropped and NaN values are added, you must specify how="outer":

all_cities = pd.merge(left=city_loc, right=city_pop, on="city", how="outer")
all_cities
state_x city lat lon population state_y
0 CA San Francisco 37.781334 -122.416728 808976.0 California
1 NY New York 40.705649 -74.008344 8363710.0 New York
2 FL Miami 25.791100 -80.320733 413201.0 Florida
3 OH Cleveland 41.473508 -81.739791 NaN NaN
4 UT Salt Lake City 40.755851 -111.896657 NaN NaN
5 NaN Houston NaN NaN 2242193.0 Texas

Of course LEFT OUTER JOIN is also available by setting how="left": only the cities present in the left DataFrame end up in the result. Similarly, with how="right" only cities in the right DataFrame appear in the result. For example:

pd.merge(left=city_loc, right=city_pop, on="city", how="right")
state_x city lat lon population state_y
0 CA San Francisco 37.781334 -122.416728 808976 California
1 NY New York 40.705649 -74.008344 8363710 New York
2 FL Miami 25.791100 -80.320733 413201 Florida
3 NaN Houston NaN NaN 2242193 Texas

If the key to join on is actually in one (or both) DataFrame’s index, you must use left_index=True and/or right_index=True. If the key column names differ, you must use left_on and right_on. For example:

city_pop2 = city_pop.copy()
city_pop2.columns = ["population", "name", "state"]
pd.merge(left=city_loc, right=city_pop2, left_on="city", right_on="name")
state_x city lat lon population name state_y
0 CA San Francisco 37.781334 -122.416728 808976 San Francisco California
1 NY New York 40.705649 -74.008344 8363710 New York New York
2 FL Miami 25.791100 -80.320733 413201 Miami Florida

Concatenation

Rather than joining DataFrames, we may just want to concatenate them. That’s what concat() is for:

result_concat = pd.concat([city_loc, city_pop])
result_concat
state city lat lon population
0 CA San Francisco 37.781334 -122.416728 NaN
1 NY New York 40.705649 -74.008344 NaN
2 FL Miami 25.791100 -80.320733 NaN
3 OH Cleveland 41.473508 -81.739791 NaN
4 UT Salt Lake City 40.755851 -111.896657 NaN
3 California San Francisco NaN NaN 808976.0
4 New York New York NaN NaN 8363710.0
5 Florida Miami NaN NaN 413201.0
6 Texas Houston NaN NaN 2242193.0

Note that this operation aligned the data horizontally (by columns) but not vertically (by rows). In this example, we end up with multiple rows having the same index (eg. 3). Pandas handles this rather gracefully:

result_concat.loc[3]
state city lat lon population
3 OH Cleveland 41.473508 -81.739791 NaN
3 California San Francisco NaN NaN 808976.0

Or you can tell pandas to just ignore the index:

pd.concat([city_loc, city_pop], ignore_index=True)
state city lat lon population
0 CA San Francisco 37.781334 -122.416728 NaN
1 NY New York 40.705649 -74.008344 NaN
2 FL Miami 25.791100 -80.320733 NaN
3 OH Cleveland 41.473508 -81.739791 NaN
4 UT Salt Lake City 40.755851 -111.896657 NaN
5 California San Francisco NaN NaN 808976.0
6 New York New York NaN NaN 8363710.0
7 Florida Miami NaN NaN 413201.0
8 Texas Houston NaN NaN 2242193.0

Notice that when a column does not exist in a DataFrame, it acts as if it was filled with NaN values. If we set join="inner", then only columns that exist in both DataFrames are returned:

pd.concat([city_loc, city_pop], join="inner")
state city
0 CA San Francisco
1 NY New York
2 FL Miami
3 OH Cleveland
4 UT Salt Lake City
3 California San Francisco
4 New York New York
5 Florida Miami
6 Texas Houston

You can concatenate DataFrames horizontally instead of vertically by setting axis=1:

pd.concat([city_loc, city_pop], axis=1)
state city lat lon population city state
0 CA San Francisco 37.781334 -122.416728 NaN NaN NaN
1 NY New York 40.705649 -74.008344 NaN NaN NaN
2 FL Miami 25.791100 -80.320733 NaN NaN NaN
3 OH Cleveland 41.473508 -81.739791 808976.0 San Francisco California
4 UT Salt Lake City 40.755851 -111.896657 8363710.0 New York New York
5 NaN NaN NaN NaN 413201.0 Miami Florida
6 NaN NaN NaN NaN 2242193.0 Houston Texas

In this case it really does not make much sense because the indices do not align well (eg. Cleveland and San Francisco end up on the same row, because they shared the index label 3). So let’s reindex the DataFrames by city name before concatenating:

pd.concat([city_loc.set_index("city"), city_pop.set_index("city")], axis=1)
state lat lon population state
San Francisco CA 37.781334 -122.416728 808976.0 California
New York NY 40.705649 -74.008344 8363710.0 New York
Miami FL 25.791100 -80.320733 413201.0 Florida
Cleveland OH 41.473508 -81.739791 NaN NaN
Salt Lake City UT 40.755851 -111.896657 NaN NaN
Houston NaN NaN NaN 2242193.0 Texas

This looks a lot like a FULL OUTER JOIN, except that the state columns were not renamed to state_x and state_y, and the city column is now the index.

The append() method is a useful shorthand for concatenating DataFrames vertically:

city_loc.append(city_pop)
state city lat lon population
0 CA San Francisco 37.781334 -122.416728 NaN
1 NY New York 40.705649 -74.008344 NaN
2 FL Miami 25.791100 -80.320733 NaN
3 OH Cleveland 41.473508 -81.739791 NaN
4 UT Salt Lake City 40.755851 -111.896657 NaN
3 California San Francisco NaN NaN 808976.0
4 New York New York NaN NaN 8363710.0
5 Florida Miami NaN NaN 413201.0
6 Texas Houston NaN NaN 2242193.0

As always in pandas, the append() method does not actually modify city_loc: it works on a copy and returns the modified copy.

Categories

It is quite frequent to have values that represent categories, for example 1 for female and 2 for male, or "A" for Good, "B" for Average, "C" for Bad. These categorical values can be hard to read and cumbersome to handle, but fortunately pandas makes it easy. To illustrate this, let’s take the city_pop DataFrame we created earlier, and add a column that represents a category:

city_eco = city_pop.copy()
city_eco["eco_code"] = [17, 17, 34, 20]
city_eco
population city state eco_code
3 808976 San Francisco California 17
4 8363710 New York New York 17
5 413201 Miami Florida 34
6 2242193 Houston Texas 20

Right now the eco_code column is full of apparently meaningless codes. Let’s fix that. First, we will create a new categorical column based on the eco_codes:

city_eco["economy"] = city_eco["eco_code"].astype('category')
city_eco["economy"].cat.categories
Int64Index([17, 20, 34], dtype='int64')

Now we can give each category a meaningful name:

city_eco["economy"].cat.categories = ["Finance", "Energy", "Tourism"]
city_eco
population city state eco_code economy
3 808976 San Francisco California 17 Finance
4 8363710 New York New York 17 Finance
5 413201 Miami Florida 34 Tourism
6 2242193 Houston Texas 20 Energy

Note that categorical values are sorted according to their categorical order, not their alphabetical order:

city_eco.sort_values(by="economy", ascending=False)
population city state eco_code economy
5 413201 Miami Florida 34 Tourism
6 2242193 Houston Texas 20 Energy
3 808976 San Francisco California 17 Finance
4 8363710 New York New York 17 Finance