'Can we fill missing values of different columns in a pandas dataframe in two/three lines of code

I hope you are doing well. I am dealing with a steel dataset having different attributes. I wanted to fill their missing values with their mean. However, rather than doing it separately I want to do it with in two or three lines of codes in a single go. I am trying the following code:

empty_list = []
empty_list.append(df.columns[df.isnull().any()])
for names in empty_list:
    df[names].fillna(df[names].mean(),axis=1,inplace=True)

First, I append the names of the columns having missing values into a list and try to iterate over that list with filling their missing values in the dataframe with their mean. But it is giving me the following error:

NotImplementedError: Currently only can fill with dict/Series column by column

Can someone have any other suggestions of how to do it. Thanks!!!!



Solution 1:[1]

empty_list here is not what you intend it to be. You should say

empty_list += list(df.columns[df.isnull().any()])

or

empty_list = df.columns[df.isnull().any()],

depending on whether empty_list previously had any values in it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Zorgoth