Fabian Bachl
Fabian Bachl

Reputation: 301

Creating an empty DataFrame as a default parameter

I am trying to create a python function that plots the data from a DataFrame. The parameters should either be just the data. Or the data and the standard deviation.

As a default parameter for the standard deviation, I want to use an empty DataFrame.

def plot_average(avg_df, stdev=pd.DataFrame()):           
    if not stdev.empty:
        ...
    ...

But implementing it like that gives me the following error message:

TypeError: 'module' object is not callable

How can an empty DataFrame be created as a default parameter?

Upvotes: 6

Views: 3902

Answers (3)

sidiyahya
sidiyahya

Reputation: 31

for a default empty dataframe :

def f1(my_df=None):
    if(my_df is None):
        my_df = pd.DataFrame()
    #stuff to do if it's not empty
    if(len(my_df) != 0):
        print(my_df)
    elif(len(my_df) == 0):
        print("Nothing")

Upvotes: 3

Fabian Bachl
Fabian Bachl

Reputation: 301

The problem lies not in the creation of a new DataFrame but in the way the function was called. I use pycharm scientific. In which I had the function call written in a block. Executing this block called the function which was, i presume, not compiled.

Executing the whole programm made it possible to call the function

Upvotes: 0

KPLauritzen
KPLauritzen

Reputation: 1869

A DataFrame is mutable, so a better approach is to default to None and then assign the default value in the function body. See https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments

Upvotes: 2

Related Questions