Sub topic 1
Series: one-dimensional labeled data
A Series is the building block of pandas. A DataFrame is a set of Series that share one index, so the behavior covered here applies to every DataFrame column. This chapter covers how a Series is built, what it stores, and how to read values from it by label or by position.
Prerequisites
This chapter assumes you have:
- Basic Python: lists, dictionaries, functions, and imports.
- A way to run Python code, either as a script or in a notebook.
- A rough idea of a table with rows and columns.
- Optionally, some NumPy knowledge. A Series wraps a NumPy-style array, but you don't need to know NumPy to follow along.
Code examples use import pandas as pd.
What a Series stores
A Series holds four things:
- Values: a one-dimensional array of data, all of one dtype.
- Index: one label for each value.
- dtype: the data type of the values, such as
int64,float64, orobject. - name: an optional label for the whole Series. It becomes the column name when the Series is placed in a DataFrame.
Here is a Series with all four parts set:
import pandas as pd
s = pd.Series([10, 20, 30], index=["a", "b", "c"], name="score")
print(s["b"]) # 20, selected by label
print(s.iloc[0]) # 10, selected by position
print(s.dtype) # int64Each part is available as an attribute:
import pandas as pd
s = pd.Series([10, 20, 30], index=["a", "b", "c"], name="score")
print(s.values) # [10 20 30]
print(s.index) # Index(['a', 'b', 'c'], dtype='object')
print(s.name) # score
print(s.shape) # (3,)
print(len(s)) # 3Creating a Series
You can build a Series from several kinds of Python data.
From a list, with the default index:
import pandas as pd
s = pd.Series([4, 8, 15])
print(s.index) # RangeIndex(start=0, stop=3, step=1)If you give no index, pandas uses a RangeIndex of the integers 0, 1, 2, and so on. These are labels. They happen to look like positions, and that causes some of the bugs described below.
From a dictionary, where keys become the index and values become the data:
import pandas as pd
prices = pd.Series({"apple": 1.2, "pear": 0.9, "plum": 2.5})
print(prices)From a scalar, which is repeated for every label in the index. The index argument is required here:
import pandas as pd
zeros = pd.Series(0, index=["a", "b", "c"])
print(zeros.tolist()) # [0, 0, 0]If the data is a list, its length must equal the index length. A mismatch raises ValueError.
Selecting by label and by position
A Series gives you two ways to read an element, and they answer different questions.
| Accessor | Meaning | Slice end |
|---|---|---|
| `s.loc[label]` | Select by index label | Inclusive |
| `s.iloc[n]` | Select by integer position | Exclusive |
| `s[key]` | Mostly label-based; avoid for anything ambiguous | Depends on key type |
Slices behave differently in the two accessors:
import pandas as pd
s = pd.Series([10, 20, 30, 40], index=["a", "b", "c", "d"])
print(s.loc["a":"c"].tolist()) # [10, 20, 30] both ends included
print(s.iloc[0:2].tolist()) # [10, 20] end excluded
print(s.loc[["a", "d"]].tolist()) # [10, 40] a list of labelsLabel slices include the end label because pandas cannot know what label would come "just before" an arbitrary label. Position slices follow normal Python rules.
The integer-index trap
When the index itself is made of integers, labels and positions can disagree:
import pandas as pd
t = pd.Series([5, 6, 7], index=[2, 1, 0])
print(t.loc[0]) # 7, the element labeled 0
print(t.iloc[0]) # 5, the first element
print(t[0]) # 7, plain [] treats integers as labels hereThe same situation arises when you filter or sort a Series with a default index. Rows keep their original labels, so after dropping the first row the label 0 no longer exists. Calling s[0] then raises KeyError.
A missing label raises KeyError. A position outside the Series raises IndexError. If you want a default instead of an exception, use s.get("z", default).
Duplicate labels
An index does not have to be unique. A Series accepts duplicate labels without complaint:
import pandas as pd
d = pd.Series([1, 2, 3], index=["a", "a", "b"])
print(d["b"]) # 3, a single label returns a scalar
print(d["a"].tolist()) # [1, 2], a repeated label returns a SeriesThe return type depends on the data. A label that appears once gives a scalar, and a label that appears twice gives a Series. Code that assumes one or the other can break when the data changes. Check d.index.is_unique if your logic depends on it.
How dtype is chosen
pandas infers the dtype from the values. You rarely need to set it at creation time, but you should know the common outcomes.
import pandas as pd
print(pd.Series([1, 2, 3]).dtype) # int64
print(pd.Series([1.5, 2, 3]).dtype) # float64
print(pd.Series([1, None, 3]).dtype) # float64, None becomes NaN
print(pd.Series([True, False]).dtype) # bool
print(pd.Series(["a", "b"]).dtype) # objectAn integer Series cannot hold a missing value with the default dtypes. When you put None in a list of integers, pandas converts the whole Series to float64 and stores the gap as NaN. This surprises people who expected to keep integers. Handling missing values is covered in its own chapter, and nullable types such as Int64 are covered in the dtype chapters.
To force a dtype at creation, pass dtype:
import pandas as pd
s = pd.Series([1, 2, 3], dtype="float64")
print(s.dtype) # float64Mutability and copies
A Series is mutable. You can assign to an existing label with loc, and assigning to a new label adds an element:
import pandas as pd
s = pd.Series([10, 20, 30], index=["a", "b", "c"])
s.loc["b"] = 99
s.loc["d"] = 40
print(s.to_dict()) # {'a': 10, 'b': 99, 'c': 30, 'd': 40}Be careful with a Series that you took from a list or array. Depending on the pandas version and the source, the Series may share memory with the original object. Call .copy() when you want a Series that is independent of its source. The chapter on copies and views explains the rules in detail.
Common errors
KeyErrorafter filtering. You looked up a label that was removed. Useilocfor "the first remaining element."- Length mismatch.
pd.Series([1, 2], index=["a"])raisesValueError. - Unexpected float dtype. A
NoneorNaNin an integer list converts the Series tofloat64. - Scalar versus Series results. Duplicate labels make
s[label]return different types. - Missing end of a slice.
locincludes the end label, andilocexcludes the end position.
Exercise
Given s = pd.Series([5, 6, 7], index=[2, 1, 0]), what do s.iloc[0], s.loc[0], and s.iloc[0:2].tolist() return? Then say what dtype pd.Series([1, None, 3]) has and why.
Show answer
s.iloc[0] is 5, because it is the first element by position. s.loc[0] is 7, because the element labeled 0 is the last one. s.iloc[0:2].tolist() is [5, 6], because the end position is excluded. pd.Series([1, None, 3]) has dtype float64, because the default integer dtype cannot store a missing value, so pandas converts the data to floats and stores the gap as NaN.