w3resource

Ensuring column uniqueness in a Pandas DataFrame


7. Checking That a Specific Column Contains Only Unique Values

Write a Pandas program to check that a specific column contains only unique values.

This exercise demonstrates how to ensure that a specific column contains only unique values by checking for duplicates.

Sample Solution :

Code :

import pandas as pd

# Create a sample DataFrame
df = pd.DataFrame({
    'ID': [1, 2, 3, 3],
    'Name': ['Orville', 'Arturo', 'Ruth', 'David']
})

# Check if the 'ID' column has unique values
unique_ids = df['ID'].is_unique

# Output the result
print(f"Is 'ID' column unique? {unique_ids}")

Output:

Is 'ID' column unique? False

Explanation:

  • Created a DataFrame with an 'ID' column that contains duplicate values.
  • Used is_unique to check if the 'ID' column contains only unique values.
  • Displayed whether the 'ID' column is unique.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to verify that a specific column contains only unique values and flag any duplicates.
  • Write a Pandas program to identify and list duplicate entries in a column that is expected to have unique values.
  • Write a Pandas program to enforce uniqueness on a specific column and output the rows that break this rule.
  • Write a Pandas program to compare the number of unique values in a column with the total row count and report discrepancies.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.