Pandas Series
A Series is pandas' one-dimensional labeled array, capable of holding any data type.
What Is a Series?
A pandas Series is a one-dimensional array-like object that can hold numbers, strings, or any other Python objects. What sets it apart from a plain Python list or a NumPy array is its index - a set of labels attached to each value, similar to a single column in a spreadsheet.
Creating a Series
The simplest way to create a Series is to pass a list to pd.Series(). If you do not specify an index, pandas automatically assigns numeric labels starting at 0, just like a Python list.
- From a list - values get an automatic integer index
- From a dictionary - the dictionary keys become the index labels
- From a NumPy array - behaves the same as a list
- With a custom index - assign your own labels via the index argument
Create a Series From a List
import pandas as pd
a = [1, 7, 2]
myvar = pd.Series(a)
print(myvar)Custom Labels (Index)
Custom Index Labels
import pandas as pd
a = [1, 7, 2]
myvar = pd.Series(a, index=["x", "y", "z"])
print(myvar)
print(myvar["y"])Once labels are assigned, you can access individual values by their label just like looking up a key in a dictionary. In fact, you can build a Series directly from a dictionary, and the keys become the labels automatically.
Create a Series From a Dictionary
import pandas as pd
calories = {"day1": 420, "day2": 380, "day3": 390}
myvar = pd.Series(calories)
print(myvar)Exercise: Pandas Series
What best describes a pandas Series?