pandasdataframemodeimputation

Change the zero values of multiple rows with mode in Pandas


I have a dataset with 10 columns. Among them I want to change the '0' values of 8 columns with mode methods. 0 is not only the values of those columns, there are other values too. Among them I only want change the 0 values with mode. Suppose the dataset looks like this,

col1  col2  col3  col4  col5  col6  col7 col8  col9  col10

I want to change the '0' values from col3 to col10 at a time.

I used the following code to change 0 to mode

replace_col = df['col3']
replace_col.replace(to_replace = 0, value = replace_col.mode()[0], inplace=True)

However, I need to change the values of df, such as df['col3'], df['col4'], df['col4'] each time. So I need to run the code 8 times to change the values of 8 columns. Is there any way I can change the value at a time running one code snippet?

Thank you.


Solution

  • import pandas as pd
    
    # Sample DataFrame
    data = {
        'col1': [1, 2, 3, 4, 5],
        'col2': [0, 6, 7, 0, 9],
        'col3': [10, 0, 0, 13, 14],
        'col4': [15, 0, 17, 18, 19],
        'col5': [0, 21, 22, 23, 0],
        'col6': [25, 0, 0, 28, 0],
        'col7': [30, 31, 0, 33, 0],
        'col8': [0, 35, 36, 0, 0],
        'col9': [40, 41, 42, 43, 44],
        'col10': [0, 51, 52, 53, 0]
    }
    
    df = pd.DataFrame(data)
    
    # Columns to update
    cols_to_update = ['col3', 'col4', 'col5', 'col6', 'col7', 'col8', 'col9', 'col10']
    
    # Replace 0 values with mode for each column
    for col in cols_to_update:
        replace_col = df[col]
        mode_value = replace_col.mode()[0]
        replace_col.replace(to_replace=0, value=mode_value, inplace=True)
    
    print(df)