w3resource

Pandas - Ensure no negative values in a DataFrame column

Pandas: Data Validation Exercise-15 with Solution

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.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/pandas/pandas-ensure-no-negative-values-in-a-dataframe-column.php