Sub topic 1
What You Are Counting: Series and DataFrame Columns
Every counting method in pandas starts from an object. The method's name looks the same on a Series and on a DataFrame, but the result differs. This chapter covers what these objects are, which one you get when you select a column, and what to check before counting anything. The later chapters on value_counts, unique, nunique and duplicated assume this model.
Prerequisites
This chapter assumes you can:
- Read and write basic Python (variables, lists, dictionaries, function calls).
- Create a pandas
Seriesand aDataFrameand import pandas aspd. - Select a column from a DataFrame with
df["name"].
You do not need to know any counting method yet. The examples were written for pandas 2.x. Differences in pandas 3 are called out where they matter.
The two objects
A Series is a one-dimensional labeled array. It has values, an index that labels each value, a dtype (the type of all values), and an optional name. A DataFrame is a table of Series that share one index. Each column is a Series, and the column labels are those Series' names.
Most counting questions are about one column: "how often does each city appear?" So the object you count is usually a Series taken from a DataFrame. A few methods also work on the whole table, and then the unit being counted changes from a value to a row.
The examples in this tutorial use one small table. This block defines it and inspects it.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Rome", "Oslo", "Paris", "Rome", "Oslo", None],
"plan": ["free", "pro", "free", "pro", "pro", "pro", "free"],
})
city = df["city"]
print(type(city)) # <class 'pandas.core.series.Series'>
print(city.name) # city
print(city.dtype) # object (the dtype is "str" in pandas 3)
print(len(city)) # 7
print(df.shape) # (7, 2): 7 rows, 2 columns
print(city.index) # RangeIndex(start=0, stop=7, step=1)The table has seven rows. The last city entry is missing, because None was passed where a value should be. That one entry affects almost every count in this tutorial.
Series or one-column DataFrame
Selecting with a single label gives a Series. Selecting with a list of labels gives a DataFrame, even if the list has one item.
as_series = df["city"] # Series
as_frame = df[["city"]] # DataFrame with one column
print(type(as_series).__name__) # Series
print(type(as_frame).__name__) # DataFrame
print(as_series.shape) # (7,)
print(as_frame.shape) # (7, 1)This matters because the same method name can return a different type depending on which you call it on. A common error is writing df[["city"]].unique() and getting an AttributeError, because unique exists only on Series.
What each method returns on each object
The following table shows what you get from each method on a Series and on a DataFrame. You will see each method in its own chapter. The table gives you the overall shape first.
| Method | On a Series | On a DataFrame |
|---|---|---|
| `count()` | One integer: non-missing values | A Series: non-missing values per column |
| `nunique()` | One integer: distinct values | A Series: distinct values per column |
| `unique()` | An array of distinct values | Not available |
| `value_counts()` | A Series of counts, indexed by value | A Series of counts, indexed by row combination |
| `duplicated()` | Boolean Series: is this value a repeat? | Boolean Series: is this row a repeat? |
| `drop_duplicates()` | A Series without repeated values | A DataFrame without repeated rows |
Two patterns to remember. First, on a Series the unit is a single value. On a DataFrame, value_counts, duplicated and drop_duplicates treat each row as the unit, while count and nunique work column by column. Second, unique is the only method in this list that has no DataFrame version.
The whole-table versions of count and nunique give a quick profile of every column at once. The block below reuses the df defined above.
print(df.count())
# city 6
# plan 7
# dtype: int64
print(df.nunique())
# city 3
# plan 2
# dtype: int64
print(df.isna().sum())
# city 1
# plan 0
# dtype: int64count gives 6 for city because it skips the missing entry. len(df["city"]) gives 7 because it counts every row. The relationship len(s) == s.count() + s.isna().sum() always holds. Check it first when counts look off by a few.
Missing values: what they look like
The last city entry is stored as None, and pandas treats it as missing. Counting methods decide whether to include missing values, and the default differs between methods. Later chapters give the rules. For now, know that pandas has several representations of "missing":
NaN(not a number) is the standard missing value in float columns and object columns.Noneis Python's missing object. In an object column it staysNone. In a numeric column pandas converts it toNaN.pd.NAis the missing value used by the nullable dtypes ("Int64","string","boolean").NaTis the missing value for datetimes.
isna() treats all four as missing, so use it to test. Do not compare with == None or == float("nan"). NaN is not equal to itself, so the comparison is always False.
The dtype can also change when a value is missing:
ints = pd.Series([1, 2, 2, None])
print(ints.dtype) # float64, because NaN is a float
print(ints.tolist()) # [1.0, 2.0, 2.0, nan]
kept_ints = pd.Series([1, 2, 2, None], dtype="Int64")
print(kept_ints.dtype) # Int64
print(kept_ints.tolist()) # [1, 2, 2, <NA>]An integer column with a gap becomes float64. Counting then reports 1.0 and 2.0 instead of 1 and 2. If you need integers to stay integers, use the nullable Int64 dtype.
The result is also a Series
Most counting results are themselves Series or DataFrames, so you can index, sort and filter them like any other data. A call such as df["city"].value_counts() returns a Series whose index holds the distinct values and whose data holds the counts. The index has the original column name, and the Series name is "count" in pandas 2.x. In pandas 1.x the Series name was the original column name instead. If code you inherited relies on that name, check the pandas version first.
Because the answer is a Series, you can chain operations on it. This chapter stays at the object level, so the example only shows the type:
result = df["city"].value_counts()
print(type(result).__name__) # Series
print(result.index.name) # city
print(result.name) # countChoosing the right object before you count
Run this short check before you pick a method:
- Which column holds the thing you are counting? Select it with a single label to get a Series.
- What is the unit: a value in one column, or a whole row? Single-column questions use the Series methods. Row-level questions use the DataFrame, optionally with
subset=to choose which columns define a row. - Do missing values count as items? Check with
isna().sum(), and read the default of each method you plan to use. - Is the dtype what you expect? Check
dtype. A numeric column stored as text (or an integer column turned into float) changes what counts as the same value.
Exercise
Given df from this chapter, what do len(df["city"]), df["city"].count() and df["city"].isna().sum() return, and what type does df[["city"]].count() return?
Show answer
len(df["city"]) is 7 (all rows), df["city"].count() is 6 (non-missing values), and df["city"].isna().sum() is 1 (the missing entry), so 6 + 1 = 7. df[["city"]] is a one-column DataFrame, so its count() returns a Series (with the single entry city 6), not a plain integer.
Exercise
A colleague writes df[["plan"]].unique() and gets an AttributeError. What went wrong, and how do you fix it?
Show answer
The double brackets select a DataFrame, and DataFrame has no unique method. Select a Series with a single label instead: df["plan"].unique().