Home »
Python »
Python Programs
Return max of zero or value for a pandas DataFrame column
Given a pandas dataframe, we have to get the max of zero or value for its column.
By Pranit Sharma Last updated : October 03, 2023
Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.
Problem statement
Here, we are given a DataFrame with multiple columns and we need to replace the negative values in this pandas DataFrame with zero.
Returning the max of zero or value for a DataFrame column
We can use the pandas.DataFrame.clip() method of dataframe.
The pandas.DataFrame.clip() is used to trim values at specified input threshold. We can use this function to put a lower limit and upper limit on the values that any cell can have in the dataframe. So we will first create a DataFrame with some positive and negative values and then we will update the column of this DataFrame by using the chain method inside which we will assign 0 as the lower limit value.
Let us understand with the help of an example,
Python program to get the max of zero or value for a pandas DataFrame column
# Importing pandas package
import pandas as pd
# Importing numpy package
import numpy as np
# Creating a dictionary
d = {'value': np.arange(-5,5)}
# Creating a DataFrame
df = pd.DataFrame(d)
# Display dataframe
print('Original DataFrame:\n',df,'\n')
# Replacing negative values
df['value'] = df['value'].clip(0, None)
# Display result
print('Result:\n',df,'\n')
Output
The output of the above program is:
Python Pandas Programs »