Skip to content Skip to sidebar Skip to footer

Creating Pandas Dataframe With A Function Throwing 'df Not Defined' Error

I have created a function as below to create a dataframe from a bigger dataframe def prepare_data(cyl,typ): global variable_name global variable_name2 mask_bel1800 = (data_train_be

Solution 1:

I think your function is missing the return statement so it returns None. You also need to assign the return value of a function to a variable to be able to use it later. For example:

defprepare_data(data, cyl, typ):
    mask = (data['Cyl'] == cyl) & (data['Typ'] == typ)
    prepared = data.loc[mask, :]
    print(f'Dataframe {cyl}_{typ}_full created.')
    return prepared

Now you will be able to call the function and print the result like this:

df = prepare_data(data_train, cyl, typ)
print(df)

The function uses data_train, cyl and typ as the input and returns prepared. That means that df outside the function is now what prepared was inside the function.

Post a Comment for "Creating Pandas Dataframe With A Function Throwing 'df Not Defined' Error"