Search code examples
pythonfunctionlambdafillna

Convert a lambda function to a regular function


I'm trying to understand how can I convert a lambda function to a normal one. I have this lambda function that it supposed to fill the null values of each column with the mode

def fill_nn(data):
    df= data.apply(lambda column: column.fillna(column.mode()[0]))
    return df

I tried this:

def fill_nn(df):
    for column in df:
        if df[column].isnull().any():
            return df[column].fillna(df[column].mode()[0])

Solution

  • Hi 👋 Hope you are doing well!

    If I understood your question correctly then the best possible way will be similar to this:

    import pandas as pd
    
    
    def fill_missing_values(series: pd.Series) -> pd.Series:
        """Fill missing values in series/column."""
    
        value_to_use = series.mode()[0]
        return series.fillna(value=value_to_use)
    
    
    df = pd.DataFrame(
        {
            "A": [1, 2, 3, 4, 5],
            "B": [None, 2, 3, 4, None],
            "C": [None, None, 3, 4, None],
        }
    )
    
    df = df.apply(fill_missing_values)  # type: ignore
    
    print(df)
    #    A    B    C
    # 0  1  2.0  3.0
    # 1  2  2.0  3.0
    # 2  3  3.0  3.0
    # 3  4  4.0  4.0
    # 4  5  2.0  3.0
    

    but personally, I would still use the lambda as it requires less code and is easier to handle (especially for such a small task).