Home > Net >  How to assign variable to a function's return object and ignore displays
How to assign variable to a function's return object and ignore displays

Time:11-02

Currently my function is something like this

def create_dataframe():
    df1 = pd.DataFrame(x)
    display(df1)
    df2 = pd.DataFrame(x_2)
    display(df2)
    df3 = pd.DataFrame(x_3)
    return df3

I want to later on in a future cell set a variable to equal only df3, but if I run the function it will of course display both dataframes 1 and 2. I only want to display those dataframes once before I then set df3 equal to a variable without the displays popping up, for example :

correct_df = create_dataframe()

which should just give me df3 and not the displays

CodePudding user response:

It is tricky and error prone to cleanly determine whether a variable exists. The most explicit would be to use a flag:

def create_dataframe(show=False):
    if show:
        df1 = pd.DataFrame(x)
        display(df1)
        df2 = pd.DataFrame(x_2)
        display(df2)
    df3 = pd.DataFrame(x_3)
    return df3

# first time
df3 = create_dataframe(show=True)

# others
df3 = create_dataframe()
  • Related