Atharva Bhagwat

Stage 0: Python building blocks

0Plan
Stage 0Core
★★

Learn the small pieces everything else is built from: values, lists, dictionaries, libraries and tables.

Every analysis in this guide is made of a few small pieces. In this stage you will meet them one at a time, from the simplest to the most useful, and see how each one leads to the next:

StepWhat it isExample
1. valueOne thing: a number, some text, or yes/no.length = 30
2. listSeveral values in order.[36, 36, 30, 33]
3. dictionaryValues with names attached.{"geneA": 36}
4. libraryExtra tools other people wrote, such as numpy.np.mean(lengths)
5. tableRows and columns, like a spreadsheet (pandas).genes["length"]

Step 1: values

A variable is a name that holds a value. The = sign means "store this under that name". Text always goes inside quotes.

run this
gene = "geneC"            # text
length = 30               # a whole number
is_long = length > 32     # True or False
print(gene, length, is_long)

Step 2: lists

A list holds several values in order, inside square brackets. Counting starts at 0, not 1.

run this
names = ["geneA", "geneB", "geneC", "geneD"]
lengths = [36, 36, 30, 33]

print(names[0])       # the first item
print(lengths[2])     # the third item
print(len(lengths))   # how many items

Step 3: dictionaries

A dictionary keeps values under names, so you can look things up by name instead of by position. It uses curly brackets { }, with name: value pairs.

run this
length_of = {"geneA": 36, "geneB": 36, "geneC": 30, "geneD": 33}

print(length_of["geneB"])

Step 4: libraries

Python on its own is small. A library is a collection of extra tools that other people wrote and shared. You load one with import. Here is numpy, a library for numbers. You do not need to memorise it: just see how it is used.

run this
import numpy as np

lengths = [36, 36, 30, 33]

print(np.mean(lengths))     # the average
print(np.max(lengths))      # the biggest
print(np.sum(lengths))      # the total

Step 5: tables with pandas

pandas is the library for tables. A table is called a DataFrame: rows are things you measured, columns are what you measured about them. Here is a table of four short DNA sequences. Notice that you build it from the lists and dictionaries you just learned.

run this
import pandas as pd

genes = pd.DataFrame({
    "gene": ["geneA", "geneB", "geneC", "geneD"],
    "sequence": [
    "ATGAAATTTAAAGAAATTATTAAAGAAGTTAAAAAA",
    "ATGGGCGCCGGCCGCGCCGGGCCCGGCGCCGCCGGC",
    "ATGACCGAATGGCTGTAATGCCGTAACGAT",
    "ATGGTGCTGAGCCCGGAAGATAAAACCAACGTG",
    ],
})
genes

A new column is just maths on an existing column. Here we count letters, then work out the GC fraction: the share of letters that are G or C.

run this
genes["length"] = genes["sequence"].str.len()
genes["g"] = genes["sequence"].str.count("G")
genes["c"] = genes["sequence"].str.count("C")
genes["gc"] = (genes["g"] + genes["c"]) / genes["length"]
genes

To keep only some rows, put a condition inside square brackets. The condition gives True or False for every row, and only the True rows stay.

run this
genes[genes["gc"] > 0.5]

Now practise in Colab

You have read the ideas. Next, try them. The notebook repeats the code above with a few blanks for you to fill in, then ends with small exercises. It is all about this stage. Run the cells in order.

Open the practice notebookYou need a free Google account. When it opens, choose File, then Save a copy in Drive, so your work is yours.

Exercises

These are also in the notebook. Try each one yourself before you open the solution.

Link names to lengths

A dictionary links a name to a value. Make one for three genes, then look one up.
Show a solution (try it first)

The output should look like this:

expected output
30
one solution
names = ["geneA", "geneB", "geneC"]
lengths = [36, 36, 30]

length_of = {"geneA": 36, "geneB": 36, "geneC": 30}
print(length_of["geneC"])

Add a column and filter a table

Add a new column to a table, then keep only the rows you care about.
Show a solution (try it first)

The output should look like this:

expected output
    gene  length  codons
0  geneA      36    12.0
1  geneB      36    12.0
3  geneD      33    11.0
one solution
import pandas as pd

genes = pd.DataFrame({
    "gene": ["geneA", "geneB", "geneC", "geneD"],
    "length": [36, 36, 30, 33],
})

genes["codons"] = genes["length"] / 3
print(genes[genes["codons"] >= 11])

Check your understanding

First star

Using your genes table, what is the GC fraction of geneC, to 3 decimal places?

Stuck? Nudge and solution

Keep the row where gene equals "geneC" and look at its gc column.

one way to get it
print(genes[genes["gene"] == "geneC"]["gc"])

Special thanks to Nilay!