w3resource

Verifying numeric range in a column using Pandas


12. Verifying Numeric Range in a DataFrame Column

Write a Pandas program to verify numeric range in a DataFrame column.

This exercise demonstrates how to verify that all values in a numerical DataFrame column fall within a specific range.

Sample Solution :

Code :

import pandas as pd

# Create a sample DataFrame with numeric data
df = pd.DataFrame({
    'Score': [85, 90, 95, 100, 110]
})

# Verify that all scores are between 0 and 100
valid_scores = df['Score'].between(0, 100)

# Output the result
print(valid_scores)

Output:

0     True
1     True
2     True
3     True
4    False
Name: Score, dtype: bool

Explanation:

  • Created a DataFrame with 'Score' values.
  • Used between() to check that all scores fall between 0 and 100.
  • Outputted a Boolean Series indicating whether each score meets the range condition.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to verify that all values in a numeric column fall within a specific range and flag those that do not.
  • Write a Pandas program to validate numeric ranges and replace out-of-range values with the column mean.
  • Write a Pandas program to check that numeric values fall within a custom range and output a summary of violations.
  • Write a Pandas program to enforce a numeric range in a column and create a new column that marks valid and invalid rows.

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.