Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: How to replace Zero values in a column with the mean of that column, For all columns with Zero Value

Tags:

python

pandas

I have a dataframe with multiple values as zero. I want to replace the values that are zero with the mean values of that column Without repeating code. I have columns called runtime, budget, and revenue that all have zero and i want to replace those Zero values with the mean of that column.

Ihave tried to do it one column at a time like this:

    print(df['budget'].mean())    
    -> 14624286.0643    
    df['budget'] = df['budget'].replace(0, 14624286.0643)    

Is their a way to write a function to not have to write the code multiple time for each zero values for all columns?

like image 759
BobbyGee Avatar asked Mar 24 '19 00:03

BobbyGee


People also ask

How do you replace zeros in Pandas?

Replace NaN Values with Zero on pandas DataFrame Use the DataFrame. fillna(0) method to replace NaN/None values with the 0 value. It doesn't change the object data but returns a new DataFrame.

How do you replace values in a DataFrame column based on condition?

You can replace values of all or selected columns based on the condition of pandas DataFrame by using DataFrame. loc[ ] property. The loc[] is used to access a group of rows and columns by label(s) or a boolean array. It can access and can also manipulate the values of pandas DataFrame.


1 Answers

Same we can achieve directly using replace method. Without fillna

df.replace(0,df.mean(axis=0),inplace=True)

Method info: Replace values given in "to_replace" with "value".

Values of the DataFrame are replaced with other values dynamically. This differs from updating with .loc or .iloc which require you to specify a location to update with some value.

like image 57
Prathamesh Ketgale Avatar answered Oct 21 '22 04:10

Prathamesh Ketgale