Atharva Bhagwat

Stage 3: Tables with pandas

0Plan
Stage 3Core
★★

Load a table, look around, pick columns and keep only the rows you want.

This stage uses a small made-up experiment. Each row is one named item measured once. The four columns bin1_count to bin4_count say how many reads fell into four brightness buckets, from the lowest signal (bin 1) to the highest (bin 4). You do not need to know where the numbers came from: the point is learning to work with a table.

Load the table

pd.read_csv reads a CSV file (a plain-text table) into a DataFrame. It can read straight from a web address:

run this
import pandas as pd

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

Look before you touch

Before doing anything, find out what you have. Run each line in its own cell:

run these
df.head()                          # the first 5 rows
df.shape                           # (number of rows, number of columns)
df.columns                         # the column names
df.info()                          # types of each column, and missing values
df.describe()                      # averages, minimums and maximums
df["variant_type"].value_counts()  # how many rows of each kind

Pick columns

run this
print(df["variant"])                     # one column
print(df[["variant", "replicate"]])       # several columns: note the double brackets

Keep only some rows

A comparison on a column gives True or False for every row. Putting that inside square brackets keeps the True rows. This is called a filter, and you will use it constantly.

run this
is_nonsense = df["variant_type"] == "nonsense"
df[is_nonsense]

To combine two conditions use & (and) or | (or), and put each condition in round brackets:

run this
df[(df["variant_type"] == "missense") & (df["replicate"] == 1)]

Sort

run this
df.sort_values("bin1_count", ascending=False)   # biggest first

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.

List the nonsense variants

Show the names of the variants whose variant_type is nonsense, each name once.
Show a solution (try it first)

The output should look like this:

expected output
<StringArray>
['p.Trp18Ter', 'p.Gln36Ter', 'p.Tyr52Ter']
Length: 3, dtype: str
one solution
import pandas as pd

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

nonsense = df[df["variant_type"] == "nonsense"]
print(nonsense["variant"].unique())

Find the top three

Among the missense rows of replicate 2, which three variants have the most reads in bin1_count?
Show a solution (try it first)

The output should look like this:

expected output
17    p.Leu25Pro
20    p.Gly46Arg
18    p.Val30Asp
Name: variant, dtype: str
one solution
import pandas as pd

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

rows = df[(df["variant_type"] == "missense") & (df["replicate"] == 2)]
rows = rows.sort_values("bin1_count", ascending=False)
print(rows["variant"].head(3))

Check your understanding

First star

How many rows are missense and from replicate 2?

Stuck? Nudge and solution

Two conditions joined with &, each in round brackets. Then count the rows with len(...).

one way to get it
rows = df[(df["variant_type"] == "missense") & (df["replicate"] == 2)]
print(len(rows))

Special thanks to Nilay!