Change the zero values of multiple rows with mode in Pandas

52 views Asked by At

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.

3

There are 3 answers

0
Shahriyar Shamsipour On BEST ANSWER
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)
0
BENY On

In your case do

df = df.mask(df==0,df.mask(df==0).mode().loc[0],axis=1)
0
ragas On

Here my answer:

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)

print(df)
df1 = df.copy()
cols = df.columns
# inplace of 999999 you can put anything
df1[cols] = df1[cols].replace(0, 999999)
print(df1)

 col1    col2    col3    col4    col5    col6    col7    col8  col9   col10
0     1  999999      10      15  999999      25      30  999999    40  999999
1     2       6  999999  999999      21  999999      31      35    41      51
2     3       7  999999      17      22  999999  999999      36    42      52
3     4  999999      13      18      23      28      33  999999    43      53
4     5       9      14      19  999999  999999  999999  999999    44  999999