Series
The basic building block in pandas is a pd.Series
, which is a one-dimensional array of data paired with a pd.Index
. The index labels can be used as a simplistic way to look up values in the pd.Series
, much like the Python dictionary built into the language uses key/value pairs (we will expand on this and much more pd.Index
functionality in Chapter 2, Selection and Assignment).
The following section demonstrates a few ways of creating a pd.Series
directly.
How to do it
The easiest way to construct a pd.Series
is to provide a sequence of values, like a list of integers:
pd.Series([0, 1, 2])
0 0
1 1
2 2
dtype: int64
A tuple is another type of sequence, making it valid as an argument to the pd.Series
constructor:
pd.Series((12.34, 56.78, 91.01))
0 12.34
1 56.78
2 91.01
dtype: float64
When generating sample data, you may often reach for the Python range
function:
pd.Series(range(0, 7, 2))
0 0
1 2
2 4
3 6
dtype: int64
In all of the examples so far, pandas will try and infer a proper data type from its arguments for you. However, there are times when you will know more about the type and size of your data than can be inferred. Providing that information explicitly to pandas via the dtype=
argument can be useful to save memory or ensure proper integration with other typed systems, like SQL databases.
To illustrate this, let’s use a simple range
argument to fill a pd.Series
with a sequence of integers. When we did this before, the inferred data type was a 64-bit integer, but we, as developers, may know that we never expect to store larger values in this pd.Series
and would be fine with only 8 bits of storage (if you do not know the difference between an 8-bit and 64-bit integer, that topic will be covered in Chapter 3, Data Types). Passing dtype="int8"
to the pd.Series
constructor will let pandas know we want to use the smaller data type:
pd.Series(range(3), dtype="int8")
0 0
1 1
2 2
dtype: int8
A pd.Series
can also have a name attached to it, which can be specified via the name=
argument (if not specified, the name defaults to None
):
pd.Series(["apple", "banana", "orange"], name="fruit")
0 apple
1 banana
2 orange
Name: fruit, dtype: object