pandas · Lesson 1.1
Series
Labelled columns of values: create them, read them by label, and summarise them.
1Make a Series
pd.Series(values, index=labels) makes a Series. Without an index, the labels are 0, 1, 2 and so on.
import pandas as pd sales = pd.Series([120, 95, 143], index=["Mon", "Tue", "Wed"]) sales
Practice
Make a Series of the temperatures [18.5, 21.0, 19.2] labelled "Lisbon", "Porto" and "Faro", and store it in result.
import pandas as pd result = ...
2Read by label
series["label"] reads one value by its label, and a list of labels reads several. This is what makes a Series more than a list.
import pandas as pd
stock = pd.Series({"tea": 12, "mug": 0, "cake": 7})
print(stock["cake"])
print(stock[["tea", "cake"]].tolist())Practice
Store the value for "Mar" in result.
import pandas as pd
visits = pd.Series({"Jan": 410, "Feb": 395, "Mar": 520, "Apr": 470})
result = ...3Summaries
Series have the summaries you'd expect: .sum(), .mean(), .median(), .min(), .max(), .std(). .idxmax() gives the label of the largest value.
import pandas as pd
visits = pd.Series({"Jan": 410, "Feb": 395, "Mar": 520, "Apr": 470})
print(visits.mean(), visits.median())
print(visits.idxmax())Practice
Store the label of the month with the fewest visits in result.
import pandas as pd
visits = pd.Series({"Jan": 410, "Feb": 395, "Mar": 520, "Apr": 470})
result = ...4Labels line up
When you combine two Series, pandas matches them by label, not by position. A label missing on one side gives NaN (missing).
import pandas as pd
march = pd.Series({"tea": 120, "mug": 30, "cake": 45})
april = pd.Series({"cake": 50, "tea": 110, "jam": 12})
march + aprilCommon mistake
Combining Series from different sources can silently line up the wrong way or create NaNs. Check the labels, or use .add(other, fill_value=0) to treat missing labels as 0.
Practice
Add the two months together so that a product missing from one month counts as 0 there. Store the result.
import pandas as pd
march = pd.Series({"tea": 120, "mug": 30, "cake": 45})
april = pd.Series({"cake": 50, "tea": 110, "jam": 12})
result = ...