Lesson 3 of 6 · about 20 minutes
Summary functions and maps
Summary functions
pandas can sum up a whole column in a single call. describe() gives the main statistics at once:
import pandas as pd
sales = pd.DataFrame({
"fruit": ["apple", "banana", "apple", "cherry", "banana", "apple"],
"boxes": [12, 7, 9, 4, 10, 15],
"price": [2.5, 1.2, 2.5, 6.0, 1.2, 2.4],
})
print(sales["boxes"].describe())The output:
count 6.000000
mean 9.500000
std 3.834058
min 4.000000
25% 7.500000
50% 9.500000
75% 11.500000
max 15.000000
Name: boxes, dtype: float64count is how many values there are, mean the average, std how spread out they are, and the rest are the smallest value, the quartiles and the largest value.
You can also ask for each one on its own:
import pandas as pd
boxes = pd.Series([12, 7, 9, 4, 10, 15])
print(boxes.sum(), boxes.mean(), boxes.max(), boxes.min())
print(boxes.median())The output:
57 9.5 15 4
9.5Counting values
For text columns, the questions are different: which values appear, and how often?
import pandas as pd
fruit = pd.Series(["apple", "banana", "apple", "cherry", "banana", "apple"])
print(fruit.unique())
print(fruit.nunique())
print(fruit.value_counts())The output:
['apple' 'banana' 'cherry']
3
apple 3
banana 2
cherry 1
Name: count, dtype: int64unique() lists the different values, nunique() counts them, and value_counts() says how often each one appears, most common first. value_counts() is one of the most used lines in all of data analysis.
Quick check
Which method tells you how many times each value appears in a column?
Maths on whole columns
Arithmetic on a column happens to every value at once. No loop needed:
import pandas as pd
sales = pd.DataFrame({"boxes": [12, 7, 9], "price": [2.5, 1.2, 6.0]})
sales["income"] = sales["boxes"] * sales["price"]
sales["vs_average"] = sales["boxes"] - sales["boxes"].mean()
print(sales)The output:
boxes price income vs_average
0 12 2.5 30.0 2.666667
1 7 1.2 8.4 -2.333333
2 9 6.0 54.0 -0.333333This is much faster than a Python loop, and it is the first thing to try before reaching for map() or apply().
map()
map() runs a function on every value of a Series and gives back a new Series. A lambda is a quick way to write a small function in place:
import pandas as pd
prices = pd.Series([2.5, 1.2, 6.0])
print(prices.map(lambda p: p * 2))
sizes = pd.Series(["S", "L", "M", "S"])
print(sizes.map({"S": "small", "M": "medium", "L": "large"}))The output:
0 5.0
1 2.4
2 12.0
dtype: float64
0 small
1 large
2 medium
3 small
dtype: objectAs the second example shows, you can also give map() a dictionary: every value is looked up in it and replaced.
Quick check
What does this print?
s = pd.Series(["y", "n", "y"])
print(list(s.map({"y": True, "n": False})))apply()
apply() with axis=1 runs a function on every row of a DataFrame. Use it when the answer depends on more than one column:
import pandas as pd
sales = pd.DataFrame({"fruit": ["apple", "cherry", "banana"], "boxes": [12, 4, 10]})
def label(row):
if row["boxes"] >= 10:
return row["fruit"] + ": plenty"
return row["fruit"] + ": running low"
print(sales.apply(label, axis=1))The output:
0 apple: plenty
1 cherry: running low
2 banana: plenty
dtype: objectText columns can also be combined directly with +, for example sales["fruit"] + " x" + sales["boxes"].astype(str).
Exercise 1: The average
Print the average (mean) of the score column, and store the highest score in a variable called best.
Exercise 2: Most popular pet
Store how many times each animal appears in a Series called counts (use value_counts()), then print the name of the most common animal.
Exercise 3: Pass or fail
Add a column result to df that is pass when the score is 50 or more and fail otherwise. Use map() on the score column.
Lesson 3 complete
You finished summary functions and maps and passed every exercise.
What you learned
describe(),mean(),median(),sum(),min()andmax()summarise a column.unique(),nunique()andvalue_counts()describe a text column.- Arithmetic on columns works on every value at once.
series.map(function or dict)transforms every value.df.apply(function, axis=1)runs a function on every row.