Exploring & Sorting a Series
Peek at data with head/tail/sample, count categories with value_counts, find distinct values with unique/nunique, and order with sort_values/sort_index.
Once you have a Series, the first job is exploring it: what does it look like, which values are most common, how many different values are there, who is on top? These methods are used constantly — on every column of every dataset you load.
Definition
head/tail/sample return a small part of a Series (first, last or random rows). value_counts returns how many times each distinct value occurs. unique returns the distinct values and nunique counts them. sort_values orders a Series by its values and sort_index by its labels. All of these return new objects and leave the original unchanged.
- Return new objects —
runs.sort_values()does not reorderruns; store the result:runs = runs.sort_values(). - Distinct values — each value counted once (
MI, MI, CSK→MI, CSK).
Syntax
python
s.head(n=5) s.tail(n=5) s.sample(n=None, frac=None, random_state=None)
s.value_counts(normalize=False, sort=True, ascending=False, dropna=True)
s.unique() s.nunique(dropna=True)
s.sort_values(ascending=True, na_position="last")
s.sort_index(ascending=True)
s.nlargest(n=5) s.nsmallest(n=5)| Method / parameter | Meaning | Default |
|---|---|---|
head(n) / tail(n) | first / last n elements | 5 |
sample(n) | n random elements | 1 |
sample(frac=0.5) | a random fraction of the elements | — |
random_state | seed so the "random" result is repeatable | None |
value_counts(normalize=True) | proportions (0–1) instead of counts | False |
value_counts(ascending=True) | least frequent first | False |
dropna=False | also count missing values | True (ignore NaN) |
sort_values(ascending=False) | largest first | True (smallest first) |
na_position | put NaN "first" or "last" | "last" |
nlargest(n) / nsmallest(n) | top / bottom n values, already sorted | 5 |
Example — head, tail and sample
python
import pandas as pd
runs = pd.Series([45, 78, 12, 101, 33],
index=["Rohit", "Virat", "Gill", "Pant", "Hardik"])
print(runs.head(3))
print(runs.tail(2))
print(runs.sample(2, random_state=42))text
Rohit 45
Virat 78
Gill 12
dtype: int64
Pant 101
Hardik 33
dtype: int64
Virat 78
Hardik 33
dtype: int64How it works: head and tail return the first/last rows in their current order. sample picks rows at random — without random_state you get different rows on every run; with random_state=42 the result is reproducible.
Example — value_counts: who won the most titles?
python
winners = pd.Series(["CSK", "MI", "KKR", "MI", "CSK", "MI",
"SRH", "CSK", "MI", "GT", "CSK", "KKR"])
print(winners.value_counts())
print(winners.value_counts(normalize=True).round(3))text
CSK 4
MI 4
KKR 2
SRH 1
GT 1
Name: count, dtype: int64
CSK 0.333
MI 0.333
KKR 0.167
SRH 0.083
GT 0.083
Name: proportion, dtype: float64How it works: value_counts groups identical values, counts them and sorts from most to least frequent. The result is a new Series: the distinct values become the index, and its name is count (or proportion with normalize=True). Missing values are ignored unless you pass dropna=False. This is the quickest way to understand any categorical column (team, venue, toss decision…).
Example — unique and nunique
python
print(winners.unique())
print(winners.nunique())
print(len(winners))text
<StringArray>
['CSK', 'MI', 'KKR', 'SRH', 'GT']
Length: 5, dtype: str
5
12How it works: unique() returns each distinct value once, in order of first appearance (not sorted). nunique() returns how many there are. len counts all 12 entries.
Note (pandas 3): for a
strSeries,unique()returns a pandasStringArray(printed as above). Old tutorials show a NumPy array likearray(['CSK', 'MI', ...], dtype=object). Call.tolist()if you want a plain list. For numeric Series it is still a NumPy array.
Example — sort_values and sort_index
python
print(runs.sort_values())
print(runs.sort_values(ascending=False))
print(runs.sort_index())text
Gill 12
Hardik 33
Rohit 45
Virat 78
Pant 101
dtype: int64
Pant 101
Virat 78
Rohit 45
Hardik 33
Gill 12
dtype: int64
Gill 12
Hardik 33
Pant 101
Rohit 45
Virat 78
dtype: int64How it works: sort_values orders by the numbers (labels travel with their values). sort_index orders by the labels — alphabetically here. Both default to ascending.
Example — top N
python
print(runs.sort_values(ascending=False).head(3))
print(runs.nlargest(3))
print(runs.nsmallest(2))text
Pant 101
Virat 78
Rohit 45
dtype: int64
Pant 101
Virat 78
Rohit 45
dtype: int64
Gill 12
Hardik 33
dtype: int64nlargest(n) is a shortcut for "sort descending, take the head" — and is faster on big data.
Comparison
| Need | Use |
|---|---|
| First / last few rows | head(n) / tail(n) |
| Random check of the data | sample(n, random_state=...) |
| Frequency of each category | value_counts() |
| Percentage of each category | value_counts(normalize=True) |
| List of distinct values | unique() |
| Number of distinct values | nunique() |
| Order by value / by label | sort_values() / sort_index() |
| Top / bottom N | nlargest(n) / nsmallest(n) |
Common mistakes
- ❌
runs.sort_values()and expectingrunsitself to change. ✅runs = runs.sort_values(). - ❌
s.sort_values(reverse=True)(Python'ssortedstyle). ✅s.sort_values(ascending=False). - ❌ Assuming
unique()is sorted. ✅ It keeps the order of first appearance; wrap withsorted(...)if needed. - ❌
len(s.unique())whenshas NaN and you want to ignore it. ✅s.nunique()ignores NaN by default (unique()includes it).
Interview tip
Q: How do you find the 3 most frequent teams in a column?
A: df["team"].value_counts().head(3) — value_counts already sorts from most to least frequent. Add normalize=True to get percentages.
Key points to remember
- head(n)/tail(n) show the first/last n values; sample(n, random_state=...) shows random ones reproducibly.
- value_counts() counts each distinct value, sorted most frequent first; normalize=True gives proportions.
- unique() returns distinct values in order of appearance; nunique() returns how many (ignoring NaN).
- sort_values() orders by value, sort_index() orders by label; ascending=False reverses.
- nlargest(n)/nsmallest(n) are fast shortcuts for top/bottom N.
- All these methods return new objects — reassign to keep the result.
- In pandas 3, unique() on a str Series returns a StringArray; use .tolist() for a plain list.
Try it yourself
Peek at a Series
IPL champions: value_counts, unique, nunique
Sorting and top N
Practice: top venues
Revision Flashcards
Tap a card to flip it and see the answer.
