Panda的info()转HTML

8
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个回答

2
一种解决方法是将info()的输出保存到可写缓冲区中(使用buf参数),然后将其转换为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")

这是文本的样子:

enter image description here

这种使用StringIO的变体可以在@jezrael的答案中找到,因此更新此答案可能没有意义。

我首先尝试了buf选项,但对我没有用。你的txt文件中包含任何文本吗? - Satyadev
我复制了你输入的完全相同的代码,但无法复现你的输出。请问你使用的是哪个版本的Python和Pandas呢? - Satyadev
2
谢谢。这一切都可以使用“StringIO”在内存中完成。 - gozzilli
是的,但你能确认它是否有效吗?我尝试了一个buffer1 = StringIO(),并将其作为buf参数传递,但出现了一些问题,当我尝试打印我的缓冲区时,我得到了一个None。 - Satyadev
啊,我在Python 2.7中使用StringIO而不是BytesIO,那就是问题所在了。无论如何,谢谢! - Satyadev
显示剩余2条评论

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")

1
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()

1

在借鉴了所有这些优秀答案的基础上,我最终采取了以下措施:

  • 去掉前三行和后两行,因为它们包含了记忆信息和其他不在表格格式中的内容(并且有固定数量的行)
  • 使用StringIO将列信息(下面代码片段中的datatype)转换为pandas的DataFrame
  • 将列重命名为“count”、“null”和“dtype”
  • 返回列信息的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可以简化,但无论如何这都实现了我所需的功能。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接