We use nunique() to count how many unique values are in a list or column. It helps us understand the variety or diversity in data.
nunique() for cardinality in Data Analysis Python
DataFrame['column_name'].nunique(dropna=True) # or for a 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 to get counts for each column.
df['City'].nunique()df.nunique()
df['Product'].nunique(dropna=False)
This program creates a small table with names, cities, and products. It then counts how many unique names, cities, and products there are. For products, it counts missing values as unique if any.
import pandas as pd # Create a simple data table data = { 'Name': ['Alice', 'Bob', 'Alice', 'David', 'Bob', None], 'City': ['NY', 'LA', 'NY', 'Chicago', 'LA', 'NY'], '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_including_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_including_na}")
If you want to count missing values as unique, set dropna=False.
nunique() is very useful to quickly check data diversity or cardinality.
It works well with pandas DataFrames and Series.
nunique() counts unique values in data.
Use it to understand how many different items or categories exist.
It can ignore or include missing values based on dropna setting.
Practice
nunique() function do when applied to a pandas DataFrame column?Solution
Step 1: Understand the purpose of
Thenunique()nunique()function counts how many distinct or unique values exist in a column.Step 2: Compare with other functions
Unlike sum or max,nunique()focuses on counting unique entries, not numerical calculations.Final Answer:
Counts the number of unique values in that column -> Option DQuick Check:
nunique()= unique count [OK]
nunique() counts unique items only [OK]- Confusing
nunique()withcount() - Thinking it sums values instead of counting unique ones
- Assuming it returns total rows instead of unique values
df?Solution
Step 1: Access the column correctly
To applynunique()on a column, first select the column usingdf['Age'].Step 2: Apply the
Then callnunique()methodnunique()as a method:df['Age'].nunique().Final Answer:
df['Age'].nunique() -> Option BQuick Check:
Correct syntax = df['column'].nunique() [OK]
nunique() [OK]- Passing column name as argument to
nunique() - Using dot notation with parentheses on column name
- Trying to index
nuniquelike a dictionary
df['City'].nunique()?
import pandas as pd
data = {'City': ['Paris', 'London', 'Paris', 'Berlin', 'London', 'Rome']}
df = pd.DataFrame(data)Solution
Step 1: Identify unique cities in the list
The cities are: 'Paris', 'London', 'Paris', 'Berlin', 'London', 'Rome'. Unique cities are 'Paris', 'London', 'Berlin', and 'Rome'.Step 2: Count unique cities
There are 4 unique cities in total.Final Answer:
4 -> Option AQuick Check:
Unique cities count = 4 [OK]
- Counting all entries instead of unique ones
- Miscounting duplicates as unique
- Confusing number of rows with unique count
import pandas as pd
data = {'Product': ['A', 'B', 'A', 'C']}
df = pd.DataFrame(data)
unique_count = df.nunique('Product')Solution
Step 1: Check how
When called on a DataFrame,nunique()works on DataFramesnunique()counts unique values for each column and does not accept column names as arguments.Step 2: Correct way to count unique values in one column
To count unique values in 'Product', select the column first:df['Product'].nunique().Final Answer:
Thenunique()method does not take column names as arguments -> Option AQuick Check:
nunique()on DataFrame has no column argument [OK]
nunique() on column, not DataFrame with argument [OK]- Passing column name as argument to
nunique()on DataFrame - Calling
nuniquewithout parentheses - Misunderstanding DataFrame constructor syntax
df with a column 'Score' containing some missing values (NaN). How do you count unique scores including the missing values as a unique category?Solution
Step 1: Understand
By default,dropnaparameter innunique()nunique()ignores missing values (NaN). Settingdropna=Falsecounts NaN as a unique value.Step 2: Apply
Usenunique()withdropna=Falsedf['Score'].nunique(dropna=False)to include NaN in the unique count.Final Answer:
df['Score'].nunique(dropna=False) -> Option CQuick Check:
Include NaN by setting dropna=False [OK]
dropna=False to count NaN as unique [OK]- Ignoring
dropnaand missing NaN count - Using
count()which excludes NaN - Using
unique()without counting length
Ready to prove it?
Pass the test and this pattern moves unknown
