how to inpute missing values based on the average value of a given row in python

To input missing values based on the average value of a given row in Python using the pandas library:

  1. Import the pandas library:
main.py
import pandas as pd
20 chars
2 lines
  1. Create a DataFrame with missing values:
main.py
df = pd.DataFrame({'A': [1, 2, None, 4, None],
                   'B': [None, 6, 7, None, 9],
                   'C': [10, None, 12, 13, None]})
145 chars
4 lines
  1. Calculate the mean value for each row and store it in a new column:
main.py
df['mean_row'] = df.mean(axis=1)
33 chars
2 lines
  1. Iterate over each row and replace missing values with the corresponding row mean:
main.py
for index, row in df.iterrows():
    for col in df.columns:
        if pd.isnull(row[col]):
            df.at[index, col] = row['mean_row']
140 chars
5 lines
  1. Remove the redundant 'mean_row' column:
main.py
df = df.drop('mean_row', axis=1)
33 chars
2 lines

The resulting DataFrame 'df' will have missing values replaced with the average value of each row.

gistlibby LogSnag