We use nunique() to count how many different values are in a list or column. It helps us understand variety in data.
nunique() for unique counts in Pandas
DataFrame['column_name'].nunique(dropna=True) # or for whole DataFrame DataFrame.nunique(dropna=True)
dropna=True means it ignores empty or missing values when counting.
You can use nunique() on a single column or on the whole DataFrame.
df['City'].nunique()df.nunique()
df['Product'].nunique(dropna=False)
This code creates a small table with names, cities, and products. It then counts how many unique names, cities, and products are in the table. For products, it counts missing values as unique if any.
import pandas as pd data = { 'Name': ['Alice', 'Bob', 'Alice', 'David', 'Bob', None], 'City': ['New York', 'Los Angeles', 'New York', 'Chicago', 'Chicago', 'Chicago'], 'Product': ['Book', 'Pen', 'Book', 'Pen', 'Notebook', 'Pen'] } df = pd.DataFrame(data) # Count unique names ignoring missing values unique_names = df['Name'].nunique() # Count unique cities unique_cities = df['City'].nunique() # Count unique products including missing values unique_products_incl_na = df['Product'].nunique(dropna=False) print(f"Unique Names: {unique_names}") print(f"Unique Cities: {unique_cities}") print(f"Unique Products (including NA): {unique_products_incl_na}")
If you want to count missing values as unique, set dropna=False.
By default, nunique() ignores missing values.
Use nunique() to quickly understand diversity in your data.
nunique() counts how many different values are in data.
It can be used on one column or the whole DataFrame.
Missing values are ignored by default but can be included.
Practice
nunique() function do in pandas?Solution
Step 1: Understand the purpose of
Thenunique()nunique()function counts how many different (unique) values exist in a pandas Series or DataFrame column.Step 2: Compare with other functions
Other options describe sum, sorting, or filling missing values, which are not whatnunique()does.Final Answer:
Counts the number of unique values in a Series or DataFrame column -> Option DQuick Check:
nunique()= unique count [OK]
- Confusing with sum() function
- Thinking it sorts data
- Assuming it fills missing values
df?Solution
Step 1: Identify correct method call on a column
To count unique values in a specific column, select the column first withdf['Age'], then callnunique().Step 2: Check syntax of options
df['Age'].nunique() uses correct syntax:df['Age'].nunique(). Other options misuse parentheses or indexing.Final Answer:
df['Age'].nunique() -> Option AQuick Check:
Usedf['column'].nunique()for unique count [OK]
nunique() [OK]- Passing column name as argument to
nunique() - Using dot notation with parentheses incorrectly
- Trying to index
nuniqueas if a dictionary
import pandas as pd
data = {'City': ['NY', 'LA', 'NY', 'Chicago', 'LA', 'NY'], 'Score': [10, 20, 10, 30, 20, 40]}
df = pd.DataFrame(data)
print(df['City'].nunique())What is the output?
Solution
Step 1: Identify unique cities in the 'City' column
The cities are ['NY', 'LA', 'NY', 'Chicago', 'LA', 'NY']. Unique values are 'NY', 'LA', and 'Chicago'.Step 2: Count unique values
There are 3 unique cities.Final Answer:
3 -> Option CQuick Check:
Unique cities count = 3 [OK]
- Counting total rows instead of unique values
- Including duplicates in count
- Confusing with number of columns
import pandas as pd
data = {'A': [1, 2, 2, 3], 'B': [4, 4, 5, 6]}
df = pd.DataFrame(data)
print(df['A'].nunique(axis=1))But it gives an error. What is the problem?
Solution
Step 1: Check
Thenunique()parametersnunique()function in pandas does not support theaxisparameter to count unique values row-wise.Step 2: Understand correct usage
It works column-wise by default. To count unique values per row, a different approach is needed.Final Answer:
Theaxisparameter is invalid fornunique()-> Option AQuick Check:
nunique()has noaxisargument [OK]
nunique() counts column-wise only [OK]- Trying to use
axis=1withnunique() - Assuming
nunique()works row-wise by default - Confusing with other functions that accept
axis
df with columns 'Name', 'City', and 'Age'. You want to find how many unique cities each person has appeared in, but the data has multiple rows per person. Which code correctly counts unique cities per 'Name'?Solution
Step 1: Understand the goal
We want to count unique cities for each person (grouped by 'Name').Step 2: Use groupby and nunique correctly
The correct syntax is to group by 'Name' and then applynunique()on the 'City' column.Step 3: Check options
df.groupby('Name')['City'].nunique() matches this syntax. Others misuse parameters or group by wrong columns.Final Answer:
df.groupby('Name')['City'].nunique() -> Option BQuick Check:
Group by 'Name', then count unique 'City' [OK]
nunique() [OK]- Using
nunique()without groupby - Passing wrong parameters to
nunique() - Grouping by 'City' instead of 'Name'
Ready to prove it?
Pass the test and this pattern moves unknown
