-1

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?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
JJJohn
  • 915
  • 8
  • 26
  • 3
    Instead of `print(df)` return `df` replace `print(df)` to `return df` inside function – Anurag Dabas Jul 10 '21 at 03:32
  • 1
    I think you're also going to want to `return df` otherwise this is locally created variable that isn't globally scoped. – Scott Boston Jul 10 '21 at 03:33
  • I'm not certain you want to import pandas inside the function only. [How is returning the output of a function different from printing it?](https://stackoverflow.com/q/750136/15497888) may be helpful as well. – Henry Ecker Jul 10 '21 at 03:40
  • 1
    @AnuragDabas Thank you, plz move your comment to answer, I'll accept it. – JJJohn Jul 10 '21 at 03:45
  • Thanks Sir but It is not necessary....Happy coding ***:)*** – Anurag Dabas Jul 10 '21 at 03:48
  • another great reason to avoid notebooks. Significant benefit comes from separating data, view – anon01 Jul 10 '21 at 05:13
  • Does this answer your question? [What is the purpose of the return statement? How is it different from printing?](https://stackoverflow.com/questions/7129285/what-is-the-purpose-of-the-return-statement-how-is-it-different-from-printing) – Karl Knechtel Aug 15 '22 at 04:48

1 Answers1

1

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()
Guy Louzon
  • 1,175
  • 9
  • 19