Atharva Bhagwat

Extra: DNA sequences with Biopython

0Plan
ExtraOptional

Optional: a library built for biology that knows how to translate DNA and read sequence files.

Biopython is a library of biology tools. You need to install it once. In Colab, run the first cell. On your own computer, use pip install biopython in your environment.

Colab cell
%pip install -q biopython

A DNA sequence as an object

A Seq behaves like text you already know how to slice, and it also knows biology:

run this
from Bio.Seq import Seq

dna = Seq("ATGACCGAATGGCTGTAATGCCGTAACGAT")

print(len(dna))
print(dna[:6])                    # slicing, like text
print(dna.reverse_complement())    # the other strand, read backwards
print(dna.translate())             # DNA to protein; * is a stop signal
print(dna.translate(to_stop=True)) # stop reading at the first stop

Reading a FASTA file

A FASTA file lists sequences: a line starting with > gives the name, then the letters follow. Here the file is a piece of text so there is nothing to upload:

a tiny FASTA file
FASTA = """>geneA low-GC test gene
ATGAAATTTAAAGAAATTATTAAAGAAGTTAAAAAA
>geneB high-GC test gene
ATGGGCGCCGGCCGCGCCGGGCCCGGCGCCGCCGGC
>geneC contains an early stop codon
ATGACCGAATGGCTGTAATGCCGTAACGAT
>geneD mixed test gene
ATGGTGCTGAGCCCGGAAGATAAAACC
AACGTG
"""
run this
from io import StringIO
from Bio import SeqIO

for record in SeqIO.parse(StringIO(FASTA), "fasta"):
    print(record.id, len(record.seq))

Sequences in a table

Collect what you want into a list of dictionaries, then turn it into a table, exactly as in Stage 0:

run this
import pandas as pd

rows = []
for record in SeqIO.parse(StringIO(FASTA), "fasta"):
    rows.append({"gene": record.id, "length": len(record.seq), "protein": str(record.seq.translate())})

seqs = pd.DataFrame(rows)
seqs

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.

Special thanks to Nilay!