Pandas Series
A Series is a one-dimensional array of values with a label for each value. You can picture it as one column of a spreadsheet: the values in the column, plus the row labels down the left side. Those labels are called the index.
Creating a Series from a list
import pandas as pd
steps = pd.Series([8200, 10450, 6300, 12010])
print(steps)0 8200
1 10450
2 6300
3 12010
dtype: int64
The left column (0, 1, 2, 3) is the default index, a counter starting at 0. The last line shows the dtype, the data type shared by every value: here int64, 64-bit integers.
You read a value with square brackets and its label:
import pandas as pd
steps = pd.Series([8200, 10450, 6300, 12010])
print(steps[1])
print(steps.values)
print(steps.index)10450
[ 8200 10450 6300 12010]
RangeIndex(start=0, stop=4, step=1)
values gives the underlying NumPy array and index describes the labels; for the default index that is a compact RangeIndex.
Custom labels
Pass index= to use your own labels. Now the labels carry meaning and you can look values up by name:
import pandas as pd
steps = pd.Series([8200, 10450, 6300, 12010],
index=["Mon", "Tue", "Wed", "Thu"],
name="steps")
print(steps)
print("Tuesday:", steps["Tue"])
print(steps[["Mon", "Thu"]])Mon 8200
Tue 10450
Wed 6300
Thu 12010
Name: steps, dtype: int64
Tuesday: 10450
Mon 8200
Thu 12010
Name: steps, dtype: int64
Passing a list of labels returns a smaller Series. The name argument labels the Series itself; it becomes the column name when the Series is placed in a DataFrame.
Creating a Series from a dictionary
A dictionary already pairs labels with values, so its keys become the index:
import pandas as pd
stock = {"apples": 40, "pears": 12, "plums": 0, "figs": 7}
s = pd.Series(stock)
print(s)
# Pick only some keys, in your own order; unknown keys become NaN
print(pd.Series(stock, index=["figs", "apples", "kiwis"]))apples 40
pears 12
plums 0
figs 7
dtype: int64
figs 7.0
apples 40.0
kiwis NaN
dtype: float64
kiwis is not in the dictionary, so pandas fills it with NaN ("not a number"), the marker for a missing value. Because NaN is a float, the whole Series became float64.
Vectorized operations
Arithmetic and comparisons apply to every element at once, with no loop:
import pandas as pd
prices = pd.Series([2.5, 4.0, 1.2], index=["tea", "cake", "water"])
print(prices * 2)
print(prices > 2)
print(prices[prices > 2])
print("Average price:", prices.mean())tea 5.0
cake 8.0
water 2.4
dtype: float64
tea True
cake True
water False
dtype: bool
tea 2.5
cake 4.0
dtype: float64
Average price: 2.566666666666667
prices > 2 produces a Series of True/False values (a boolean mask). Putting that mask inside the brackets keeps only the rows where it is True. You will use this pattern constantly.
Alignment by label
When two Series are combined, pandas matches values by label, not by position. Labels present in only one Series give NaN:
import pandas as pd
week1 = pd.Series({"ana": 3, "ben": 5, "cleo": 2})
week2 = pd.Series({"cleo": 4, "ana": 1, "dev": 6})
print(week1 + week2)
print((week1 + week2).sum())ana 4.0
ben NaN
cleo 6.0
dev NaN
dtype: float64
10.0
Even though the two Series list the names in different orders, ana was added to ana. Notice that sum() simply skipped the NaN values.
Useful Series attributes and methods
| Code | Result |
|---|---|
s.size / len(s) |
number of elements |
s.dtype |
data type |
s.head(n) / s.tail(n) |
first / last n elements |
s.sum(), s.mean(), s.max() |
aggregates (NaN skipped) |
s.idxmax() |
label of the largest value |
s.sort_values() |
values sorted |
s.to_list() |
plain Python list |
Test yourself
What is the index of pd.Series([5, 6, 7])?
- 5, 6, 7
- 0, 1, 2
- 1, 2, 3
- There is no index
What does pd.Series({"a": 1}) + pd.Series({"b": 2}) contain?
- a=1, b=2
- a=3
- a=NaN, b=NaN
- An error
Given s = pd.Series([1, 5, 3]), what does s[s > 2] return?
- [True, True, False]
- The values 5 and 3 with their labels
- The number 2
- The values 1 and 3