w3resource

Pandas - Ensure no negative values in a DataFrame column


15. Ensuring No Negative Values in a DataFrame Column

Write a Pandas program that ensures no negative values in a DataFrame column.

This exercise shows how to ensure that a column contains no negative values.

Sample Solution :

Code :

import pandas as pd

# Create a sample DataFrame with numerical values
df = pd.DataFrame({
    'Amount': [100, -50, 200, -10]
})

# Check for any negative values in the 'Amount' column
no_negatives = (df['Amount'] >= 0).all()

# Output the result
print(f"Are there any negative values? {not no_negatives}")

Output:

Are there any negative values? True

Explanation:

  • Created a DataFrame with numerical 'Amount' values, including negatives.
  • Used a condition to check if all values in the 'Amount' column are non-negative.
  • Outputted whether there are any negative values in the column.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to check that a specific numeric column contains no negative values and list any violations.
  • Write a Pandas program to replace negative values in a DataFrame column with zero and validate the change.
  • Write a Pandas program to flag rows in which a numeric column has negative values and export those rows for further analysis.
  • Write a Pandas program to validate numeric columns by ensuring no negative values exist and compute summary statistics for flagged 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.