简体   繁体   中英

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

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

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM