Df.info() is not displaying any result in st.write()

Hi,

I am trying to get information of pandas dataframe using the following code:

st.write(df.info())

But instead of printing information of dataframe it is printing “None” and the result is printed in command prompt instead.

Help me in resolving this issue.

Hi @anshul -

This occurs because this pandas function doesn’t return anything back to Python (which is why you get a value of None), it only prints. The pandas documentation for df.info() offers a similar type of solution:

Pipe output of DataFrame.info to buffer instead of sys.stdout, get buffer content and writes to a text file:

>>> import io 
>>> buffer = io.StringIO() 
>>> df.info(buf=buffer)
>>> s = buffer.getvalue() 
>>> with open("df_info.txt", "w", 
...     encoding="utf-8") as f:
...     f.write(s) 

In your case, you can probably do st.write(s) instead of writing to a file at the end.

3 Likes

I’m facing same issue, i created function which print a value

recommendation=anime_recommendation(anime_names)
if st.button("Recommend"):
     recommendations=anime_recommendation(anime_names)
     import io
     buffer = io.StringIO()
     recommendations(buf=buffer)
     s = buffer.getvalue()
     with open("recommendations.txt", "w",
        encoding="utf-8") as f:
        f.write(s)

it giving me this error:

TypeError: 'NoneType' object is not callable
Traceback:

File "c:\python39\lib\site-packages\streamlit\script_runner.py", line 354, in _run_script
    exec(code, module.__dict__)
File "D:\projects\RecommendAnime\webapp\web_app.py", line 63, in <module>
    recommendations(buf=buffer)

st.write(pd.DataFrame([{col: int(dr[col].isna().sum()) for col in dr.columns}]).T)

:wink:

This issue is solved in

randyzwitch
is right but instead of using st.write you need to use st.text, other way will display an ugly str.

solution by: snehankekre

buffer = io.StringIO()
df.info(buf=buffer)
s = buffer.getvalue()
st.text(s)

Alternatively, if you want the output as da data frame for whatever reasons you can use this code:

def get_df_info(df):
     buffer = io.StringIO ()
     df.info (buf=buffer)
     lines = buffer.getvalue ().split ('\n')
     # lines to print directly
     lines_to_print = [0, 1, 2, -2, -3]
     for i in lines_to_print:
         st.write (lines [i])
     # lines to arrange in a df
     list_of_list = []
     for x in lines [5:-3]:
         list = x.split ()
         list_of_list.append (list)
     info_df = pd.DataFrame (list_of_list, columns=['index', 'Column', 'Non-null-Count', 'null', 'Dtype'])
     info_df.drop (columns=['index', 'null'], axis=1, inplace=True)
     st.dataframe(info_df)