How to return a string from pandas.DataFrame.info ()

I would like to display the output pandas.DataFrame.info()in a text widget tkinter, so I need a string. However, pandas.DataFrame.info()returns NoneType, anyway, can I change this?

import pandas as pd
import numpy as np

data = np.random.rand(10).reshape(5,2)
cols = 'a', 'b'
df = pd.DataFrame(data, columns=cols)
df_info = df.info()
print(df_info)
type(df_info)

I would like to do something like:

info_str = ""
df_info = df.info(buf=info_str)

Is it possible to get pandasto return a string object from DataFrame.info()?

+4
source share
1 answer

The documentation you linked has an argument buf:

buf: write buffer, sys.stdout by default

Thus, one option would be to pass an instance of StringIO:

>>> import io
>>> buf = io.StringIO()
>>> df.info(buf=buf)
>>> s = buf.getvalue()
>>> type(s)
<class 'str'>
>>> print(s)
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 2 columns):
a    5 non-null float64
b    5 non-null float64
dtypes: float64(2)
memory usage: 160.0 bytes
+6
source

Source: https://habr.com/ru/post/1654291/


All Articles