pandas Series
Part of the free LogicWiz Python course, Module 10: NumPy and pandas. The examples and practice run in the app.
Shankar bhaiya reads his week of sales as "Monday ₹1200, Tuesday ₹950…", not "position 0, position 1". A NumPy array only knows positions. A pandas Series puts a label on every value.
You'll learn to
- Create a Series from a list, a dict, an ndarray or a single value
- Use index labels with `loc` and positions with `iloc`
- Do maths and filters on a Series, and see how labels line up
Learn
A Series is a labelled column
A Series is a one-dimensional array with an index: a label for every value. Think of one column of an Excel sheet together with its row names.
The convention is import pandas as pd. If you don't give labels, pandas numbers them 0, 1, 2, …. Under the hood the values are a NumPy array, so vectorised maths and masks work just as in 10.2.
Four ways to make a Series
import pandas as pd
import numpy as np
sales = pd.Series([1200, 950, 1430], index=["Mon", "Tue", "Wed"])
print(sales)
marks = pd.Series({"Riya": 82, "Kabir": 91, "Meher": 77}) # dict keys become labels
print(marks)
print(pd.Series(np.array([1.5, 2.5]))) # from an ndarray
print(pd.Series(5, index=["a", "b", "c"])) # one value, repeated
Read the printout: labels on the left, values on the right, and the dtype at the bottom.
Labels vs positions
import pandas as pd
sales = pd.Series([1200, 950, 1430, 1100], index=["Mon", "Tue", "Wed", "Thu"])
print(sales["Tue"], sales.loc["Tue"]) # by label
print(sales.iloc[0], sales.iloc[-1]) # by position
print(sales.loc["Tue":"Wed"].tolist()) # label slice: end INCLUDED
print(sales.iloc[1:2].tolist()) # position slice: end excluded
print(sales.head(2).tolist(), sales.tail(1).tolist())
print(sales.index.tolist(), sales.values, sales.size)
.tolist() turns a Series into a plain list, which is handy for short output.
Label slices include the end; position slices don't. s.loc["Tue":"Wed"] gives both days, but s.iloc[1:2] gives one value. And on a labelled Series, use s.iloc[0] for "the first value": s[0] is ambiguous. If the labels are numbers like 10, 20, it looks for the label 0 and raises KeyError. With text labels, pandas 2 still falls back to position 0 but warns that this is going away (FutureWarning), and pandas 3 removes the fallback. Always use .iloc for positions.
Maths and filters
import pandas as pd
week = pd.Series([1200, 950, 1430, 1100, 1800, 2400, 600],
index=["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"])
print(week.sum(), week.max(), round(week.mean(), 2))
print(week.idxmax(), week.idxmin()) # the LABEL of the max and min
print(week[week > 1300])
print((week * 1.05).round(1).head(2))
print(week.quantile(0.75))
Labels line up when you add
import pandas as pd
counter1 = pd.Series({"Chai": 50, "Samosa": 30})
counter2 = pd.Series({"Samosa": 20, "Dosa": 10})
print(counter1 + counter2)
print(counter1.add(counter2, fill_value=0))
pandas adds values with the same label, whatever their position. A label found in only one Series gives NaN ("not a number", a missing value), unless you pass fill_value.
CBSE IP Class 12 practicals on Series:
- Create a Series from a dictionary and from an ndarray.
- Print all elements above the 75th percentile:
s[s > s.quantile(0.75)]. - Show
head/tail, and attributes likeindex,values,size,dtype,empty.
Board papers love "predict the output" on loc vs iloc slicing.
In one line
A Series is a labelled 1D array: make it from a list, dict, ndarray or scalar; loc uses labels (slice end included), iloc uses positions; maths lines up by label.
Interview corner
What is the difference between a NumPy array and a pandas Series?
A Series wraps a 1D array and adds an index of labels, a name and missing-value handling. Operations between Series align on labels, not positions, and the index makes lookups like s["Mon"] possible. Use s.to_numpy() to get the plain array back.
What is the difference between `loc` and `iloc`?
loc selects by label and its slices include the end label; iloc selects by integer position and its slices exclude the end, like Python lists. With an integer index such as [10, 20, 30], s.loc[10] and s.iloc[0] are the same element.
What happens when you add two Series with different indexes?
pandas aligns them on the union of their labels. Labels present in only one Series give NaN, which also makes the dtype float. Use s1.add(s2, fill_value=0) to treat missing labels as 0.