import pandas as pd
import numpy as np
df = pd.DataFrame(
{"a": [1, 2, 3, np.nan],
"b": [4, np.nan, 5, 6],
"c": [7, 8, np.nan, 9]},
)
print(df)
columns = list(df.columns)
def my_function(row):
"""这个参数是每行的row"""
avg = row.mean()
for column in columns:
if np.isnan(row[column]):
row[column] = avg
return row
df[columns] = df.apply(my_function, axis=1, result_type='expand')
print(df)