Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pandas

I would like to display the output from pandas.DataFrame.info() on a tkinter text widget so I need a string. However pandas.DataFrame.info() returns NoneType is there anyway I can 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'd like to do something like:

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

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

like image 515
Jason Avatar asked Sep 11 '16 20:09

Jason


People also ask

What does INFO () do in Python?

The info() method prints information about the DataFrame. The information contains the number of columns, column labels, column data types, memory usage, range index, and the number of cells in each column (non-null values). Note: the info() method actually prints the info.

What does Pandas describe () method return?

The describe() method returns description of the data in the DataFrame. If the DataFrame contains numerical data, the description contains these information for each column: count - The number of not-empty values. mean - The average (mean) value.


1 Answers

In the documentation you linked, there's a buf argument:

buf : writable buffer, defaults to sys.stdout

So one option would be to pass a StringIO instance:

>>> 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
like image 171
DSM Avatar answered Oct 21 '22 13:10

DSM