Lesson 03
Series Attributes
Inspect a Series with index, values, dtype, size, shape, ndim, name, and empty, and take a quick look with head and tail.
Attributes describe a Series without changing it. They answer what the labels are, what the values are, what type they hold, and how many there are. None of them need brackets, because they are not method calls.
Labels and values
index gives the labels as an Index object, and values gives the data as a NumPy array. That array is the same data pandas is using, which is why a Series is as fast as an array.
import pandas as pd
stock = pd.Series([12, 0, 31, 4], index=["lamp", "pen", "bag", "mug"], name="units")
print(stock.index)
print(stock.values, type(stock.values))
print(list(stock.index))Output:
Index(['lamp', 'pen', 'bag', 'mug'], dtype='object')
[12 0 31 4] <class 'numpy.ndarray'>
['lamp', 'pen', 'bag', 'mug']Type, size, and shape
dtype is the shared type. size and len() both count the values. shape is a tuple, and ndim is always 1 for a Series.
import pandas as pd
stock = pd.Series([12, 0, 31, 4], index=["lamp", "pen", "bag", "mug"], name="units")
print(stock.dtype)
print(stock.size, len(stock))
print(stock.shape, stock.ndim)Output:
int64
4 4
(4,) 1Name and empty
name is the heading, and you can set it at any time. empty is True when there are no values at all, which is the honest way to check before you summarize.
import pandas as pd
stock = pd.Series([12, 0, 31, 4], index=["lamp", "pen", "bag", "mug"], name="units")
print(stock.name)
stock.name = "units in stock"
print(stock.name)
nothing = pd.Series(dtype="float64")
print(nothing.empty, stock.empty)Output:
units
units in stock
True FalseA quick look
head() and tail() show the first or last five values, or as many as you ask for. On a long Series this is how you check the shape of the data without printing all of it.
import pandas as pd
minutes = pd.Series(range(1, 31), name="minutes")
print(minutes.head(3))
print(minutes.tail(2))
print(minutes.count(), minutes.sum())Output:
0 1
1 2
2 3
Name: minutes, dtype: int64
28 29
29 30
Name: minutes, dtype: int64
30 465Key takeaways
-
Attributes have no brackets.
s.size, nots.size() -
valuesis a NumPy array, andindexis anIndex -
ndimis always 1 for a Series -
headandtaildefault to five values -
Previous: Creating a Series
Loading playground…
Check your understanding
Series Attributes Quiz
Which of these needs no brackets?
1 / 10