Module 3 · pandas · Lesson 21 of 66

Everyday operations

Unique values, apply, sorting, null checks and pivot tables.

In this lesson · about 16 minutes

  • Count unique values
  • Transform a column with apply
  • Sort, find nulls and build a pivot table
CodeWhat it does
df['col2'].unique()The distinct values
df['col2'].nunique()How many distinct values
df['col2'].value_counts()How often each value appears, most common first
df['col1'].apply(func)Run a function on every value (your own, len, or a lambda)
df.sort_values(by='col2')Sort rows by a column (add ascending=False for biggest first)
df.columns, df.indexThe column names and the index
del df['col1']Remove a column for good

Pivot tables

df.pivot_table(values='D', index=['A', 'B'], columns=['C']) reshapes data so that one column's values become new columns, averaging D wherever several rows land in the same cell. If you've used pivot tables in Excel, it's the same idea.

Exercise

Most common browser

Find how many visits came from each browser, most common first.

Code that runs before yours
import pandas as pd
visits = pd.DataFrame({'browser': ['Chrome', 'Safari', 'Chrome', 'Firefox', 'Chrome', 'Safari'], 'seconds': [30, 45, 12, 80, 22, 51]})

Exercise

Minutes from seconds

Add a column minutes to visits: seconds divided by 60, using .apply() with a lambda.

Code that runs before yours
import pandas as pd
visits = pd.DataFrame({'browser': ['Chrome', 'Safari', 'Chrome', 'Firefox', 'Chrome', 'Safari'], 'seconds': [30, 45, 12, 80, 22, 51]})

Exercise

Longest visits first

Sort visits by seconds, longest first.

Code that runs before yours
import pandas as pd
visits = pd.DataFrame({'browser': ['Chrome', 'Safari', 'Chrome', 'Firefox', 'Chrome', 'Safari'], 'seconds': [30, 45, 12, 80, 22, 51]})

Exercises solved: 0 of 3

Tip: solve each exercise first. Press Check to test your code.

Noviq Academy's Data Science course is free and for learning. Python runs in your browser with Pyodide, which downloads about 20 MB the first time, plus a few more for scikit-learn. Your code and progress stay on this device. The salaries data is a sample of San Francisco's public pay records; the purchases, customers, housing, advertising and classified data are made up. The Titanic, tips, flights and iris data sets come from Seaborn's examples; the maps use public 2011 to 2014 US and world figures. The 911 data is a 20,000-call sample of Montgomery County, Pennsylvania's public 911 records; the movie ratings are the MovieLens 100K data from GroupLens Research; the reviews are a 3,000-review sample from the Yelp Dataset Challenge; the loans are public LendingClub data; the colleges are the College data from An Introduction to Statistical Learning; the bank notes, kyphosis and breast cancer data come from the UCI Machine Learning Repository. Spark and TensorFlow can't run in a browser, so those lessons use stand-ins that run here, and show the code for the real tools.