Skip to content
Advertisement

How do I render the dataframe in the style at the beginning in a function?

With jupyter notebook, this code

import pandas as pd
df = pd.DataFrame([[71,62,13], [75,76,77]], columns=list("ABC"))
df

gives output in this style

enter image description here

if I put it in a function,

def prepare():
    import pandas as pd
    df = pd.DataFrame([[71,62,13], [75,76,77]], columns=list("ABC"))
    print(df)
prepare()

I get the dataframe in this style

enter image description here

How do I render the dataframe in the style at the beginning in a function?

Advertisement

Answer

The styling as you show, can be explicitly called by the head() method

Following on the comments, instead of having the function print the dataframe, you can have it return, the use the head method

Also, its a better practice to import the libraries outside of functions, but in the main file

import pandas as pd

def prepare():
    df = pd.DataFrame([[71,62,13], [75,76,77]], columns=list("ABC"))
    rerurn df

returned_df = prepare()
returned_df.head()
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement