熊猫的信息()到HTML

时间:2017-05-15 10:13:22

标签: python pandas

Pandas使用describe()上调用的DataFrame函数提供一些摘要统计信息。该函数的输出是另一个DataFrame,因此可以通过调用to_html()轻松导出到HTML。

它还会提供有DataFrame info()功能的信息,但会打印出来,返回None。有没有办法获得与DataFrame相同的信息或任何其他可以导出为HTML的方式?

以下是一个示例info()供参考:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 7 columns):
0    5 non-null float64
1    5 non-null float64
2    5 non-null float64
3    5 non-null float64
4    5 non-null float64
5    5 non-null float64
6    5 non-null float64
dtypes: float64(7)
memory usage: 360.0 bytes

4 个答案:

答案 0 :(得分:1)

解决方案可以是将info()的输出保存到可写缓冲区(使用buf参数),然后converting to html

下面使用txt文件作为缓冲区的示例,但这可以使用StringIO在内存中轻松完成。

import pandas as pd
import numpy as np

frame = pd.DataFrame(np.random.randn(100, 3), columns =['A', 'B', 'C'])

_ = frame.info(buf = open('test_pandas.txt', 'w'))   #save to txt

# Example to convert to html
contents = open("test_pandas.txt","r")
with open("test_pandas.html", "w") as e:
    for lines in contents.readlines():
        e.write("<pre>" + lines + "</pre> <br>\n")

以下是txt的外观:

enter image description here

使用StringIO的变体可以在@jezrael的答案中找到,所以可能没有必要更新这个答案。

答案 1 :(得分:1)

我尝试使用StringIO重写另一个解决方案,同时必须使用getvalue() split

from pandas.compat import StringIO

frame = pd.DataFrame(np.random.randn(100, 3), columns =['A', 'B', 'C'])

a = StringIO()
frame.info(buf = a)  

# Example to convert to html
contents = a.getvalue().split('\n')
with open("test_pandas.html", "w") as e:
    for lines in contents:
        e.write("<pre>" + lines + "</pre> <br>\n")

答案 2 :(得分:1)

根据所有这些重要答案的输入,我最终做了以下事情:

  • 剥离前三行和最后两行,因为它们包含内存信息和其他非表格格式(以及固定行数)
  • 将列信息(下面代码段中的datatype)转换为pandas&#39; DataFrame使用StringIO
  • 重命名列&#34; count&#34;,&#34; null&#34;和&#34; dtype&#34;
  • 返回列信息的html和剩余内容的明文(前3和后2)

因此有结果:

def process_content_info(content: pd.DataFrame):
    content_info = StringIO()
    content.info(buf=content_info)
    str_ = content_info.getvalue()

    lines = str_.split("\n")
    table = StringIO("\n".join(lines[3:-3]))
    datatypes = pd.read_table(table, delim_whitespace=True, 
                   names=["column", "count", "null", "dtype"])
    datatypes.set_index("column", inplace=True)

    info = "\n".join(lines[0:2] + lines[-2:-1])

    return info, datatypes

也许第二个StringIO可以简化,但无论如何这可以实现我所需要的。

答案 3 :(得分:0)

import StringIO
output = StringIO.StringIO()
#Write df.info to a string buffer
df.info(buf=output)
#put the info back to a dataframe so you can use df.to_html()
df_info =  pd.DataFrame(columns=['DF INFO'], data=output.getvalue().split('\n'))
df_info.to_html()