Atharva Bhagwat

Stage 5: Writing functions

0Plan
Stage 5Core
★★

Turn code you use more than once into a function with a name, so you write it once and use it everywhere.

In Stage 4 you scored the whole table. Next week you may want to score a different table, or ignore rows with too few reads. If you copy and paste the code, the copies drift apart and you forget which one you trust.

A tiny function

run this
def double(number):
    return number * 2

print(double(4))
print(double(10))
  • def starts the recipe, then its name, then the parameters (the things you give it) in round brackets and a colon.
  • The indented lines are the recipe.
  • return hands the answer back.
  • Calling it, double(4), runs the recipe with 4.

Our scoring recipe as a function

run this
def add_scores(df, min_reads=0):
    """Add total_reads and score columns. Rows with fewer than min_reads reads get no score."""
    df = df.copy()    # work on a copy, so the original table is not changed
    df["total_reads"] = df["bin1_count"] + df["bin2_count"] + df["bin3_count"] + df["bin4_count"]
    df["score"] = (df["bin1_count"] * 1 + df["bin2_count"] * 2 + df["bin3_count"] * 3 + df["bin4_count"] * 4) / df["total_reads"]
    df.loc[df["total_reads"] < min_reads, "score"] = None
    return df
  • min_reads=0 is a parameter with a default: if you do not say otherwise, it is 0.
  • The text in triple quotes is the docstring. It explains the function, and help(add_scores) shows it.
  • df.copy() makes a copy, so the function never changes your original table.

Use it

run this
import pandas as pd

toy = pd.read_csv("https://atharvabhagwat.dev/assets/data/toy_vampseq_bin_counts.csv")

scored = add_scores(toy)                    # no filtering
strict = add_scores(toy, min_reads=50)      # same recipe, one setting changed

print(scored[["variant", "replicate", "score"]].head())
print(strict["score"].isna().sum(), "rows have no score now")

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 covers Stages 3 to 5, so scroll to the section with this stage's number. 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.

Write a percentage function

Write a function called percent that takes two numbers, part and whole, and gives back the percentage.
Show a solution (try it first)

The output should look like this:

expected output
37.5
25.0
100.0
one solution
def percent(part, whole):
    return part / whole * 100

print(percent(3, 8))
print(percent(1, 4))
print(percent(50, 50))

Count a letter in a function

Write a function that counts how many times a letter appears in some DNA, then use it twice.
Show a solution (try it first)

The output should look like this:

expected output
2
3
one solution
def count_letter(dna, letter):
    return dna.count(letter)

print(count_letter("ATGCATGC", "A"))
print(count_letter("GGGCCC", "G"))

Check your understanding

First star

Define add_scores and run it on the toy table. What is the score of p.Ser45Thr in replicate 1, to 3 decimal places?

Stuck? Nudge and solution

Call add_scores(toy), then filter the result on both variant and replicate, and look at the score column.

one way to get it
scored = add_scores(toy)
row = scored[(scored["variant"] == "p.Ser45Thr") & (scored["replicate"] == 1)]
print(row["score"])

Special thanks to Nilay!