Search code examples
pandassklearn-pandas

Pandas Df.head() does not display when called inside the method()?


Cannot access the pandas dataframe.head() or dataframe.describe() when the call is made inside a method.
def develop_df():

    studentData = { 
    0 : {
        'name' : 'Aadi',
        'age' : 16,
        'city' : 'New york'
        },
    1 : {
        'name' : 'Jack',
        'age' : 34,
        'city' : 'Sydney'
        },
    }

    print("Now lets print student data")
    print(studentData)
    print("%" * 80)
    print("Create a df and then print head")
    st_df = pd.DataFrame(studentData)
    st_df.head()
    print("%" * 80)
develop_df()

Output:

Now lets print student data 
{0: {'name': 'Aadi', 'age': 16, 'city': 'New york'}, 1: {'name': 'Jack', 'age': 34, 'city': 'Sydney'}}
Create a df and then print head
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

But, as seen when called outside the method, it works.

studentData = { 
0 : {
    'name' : 'Aadi',
    'age' : 16,
    'city' : 'New york'
},
1 : {
    'name' : 'Jack',
    'age' : 34,
    'city' : 'Sydney'
},
 }
print("Now lets print student data")
print(studentData)
print("%" * 80)
print("Create a df and then print head")
st_df = pd.DataFrame(studentData)
st_df.head()

Output:
Now lets print student data {0: {'name': 'Aadi', 'age': 16, 'city': 'New york'}, 1: {'name': 'Jack', 'age': 34, 'city': 'Sydney'}} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Create a df and then print head 0 1 age 16 34 city New york Sydney name Aadi Jack

Any suggestion on resolving it?


Solution

  • To pretty-print within a loop, first import the display_html function:

    from IPython.display import display_html
    

    Then wrap display_html around any calls to df.head() within a function definition, for example:

    display_html(st_df.head())