python - 将标题/描述部分添加到数据框 Pandas Python

标签 python pandas dataframe pandas-styles

我想在下面的数据框 data 的标题下方放置一个 header 值并获得预期输出,我该怎么做?

import pandas as pd

class SubclassedDataFrame(pd.DataFrame):

    # normal properties
    _metadata = ['description']

    @property
    def _constructor(self):
        return SubclassedDataFrame

data = {"a": [1, 2, 3], "b": [10, 12, 13], "c": [230, 1, 3],"d": [8, 12, 9],}

df = SubclassedDataFrame(data)
title = 'Outputs'
header = 'header'

df = df.style.set_caption(title).set_table_styles([{
    'selector': 'caption',
    'props': [
        ('color', 'red'),
        ('font-size', '15px'),
        ('font-style', 'italic'),
        ('font-weight', 'bold'),
        ('text-align', 'center')
    ]
}])

display(df)

输出:

enter image description here

预期输出:

enter image description here

  header

enter image description here

最佳答案

有两种方法:

一种方法是创建一个 header 为顶层的 MultiIndex:

title = 'Outputs'
header = 'header'

# Add MultiIndex Header
df.columns = pd.MultiIndex.from_product([[header], df.columns])
styler = df.style.set_caption(title).set_table_styles([{
    'selector': 'caption',
    'props': [
        ('color', 'red'),
        ('font-size', '15px'),
        ('font-style', 'italic'),
        ('font-weight', 'bold'),
        ('text-align', 'center')
    ]
}])

display(styler)

Header as MultiIndex

这种方法保持了 pandas Styler 对象的完整性,并使“header”成为 table 对象的一部分,成为 thead 中的第一行。


第二种方法是创建一个 Subclass Styler 对象并修改 jinja 模板。

templates/myhtml.tpl:

{% extends "html_table.tpl" %}
{% block table %}
<div class="wrap">
    {% if table_title %}
    <h1 class="table-title">{{ table_title}}</h1>
    {% endif %}
    {% if table_header %}
    <h2 class="table-header">{{ table_header }}</h2>
    {% endif %}
{{ super() }}
</div>
{% endblock table %}

templates/mystyles.tpl:

{% extends "html_style.tpl" %}
{% block style %}
{{ super() }}
<style>
    .wrap {
        display: inline-block;
    }

    .table-title {
        color: red;
        font-size: 15px !important;
        font-style: italic;
        font-weight: bold;
        text-align: center;
        margin: 0 2px !important;
    }

    .table-header {
        text-align: center;
        font-size: 13px !important;
        margin: 0 2px !important;
    }
</style>
{% endblock style %}
title = 'Outputs'
header = 'header'

# Build Styler Subclass from templates
MyStyler = Styler.from_custom_template(
    "templates",               # Folder to Search
    html_table="myhtml.tpl",   # HTML Template
    html_style='mystyles.tpl'  # CSS Template
)
# Get Styler For `df`
styler = MyStyler(df)
# Render with arguments and display
HTML(styler.render(table_title=title, table_header=header))

Styled table with h1 and h2 elements

这种方法将一些控件从 Styler 对象转移到模板,但允许更大的灵 active ,因为它可用于创建 Styler 对象当前不支持的其他 HTML 元素。


环境 jupyter-notebook

设置:

import pandas as pd
from IPython.display import HTML, display
from pandas.io.formats.style import Styler


class SubclassedDataFrame(pd.DataFrame):
    # normal properties
    _metadata = ['description']

    @property
    def _constructor(self):
        return SubclassedDataFrame


data = {
    "a": [1, 2, 3],
    "b": [10, 12, 13],
    "c": [230, 1, 3],
    "d": [8, 12, 9]
}

df = SubclassedDataFrame(data)

关于python - 将标题/描述部分添加到数据框 Pandas Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69242457/

相关文章:

python - 如何从 Pool.starmap_async() 中获取结果?

python - 如何将一行 append 到另一个数据框

r - 获取存在条件的行

python - 为什么 current_url 在 Ubuntu 16.04 上引发 "No JSON object could be decoded"w/Selenium & PhantomJS?

python - 为什么我的单词中的字符不在字母表中移动一个位置?

python - 序列化包含函数的对象 - 含义

python - 使用 Sphinx 记录包 __init__ 导入

python - 在 Python Pandas 的数据帧上使用字符串方法?

python - 将 numpy.array 存储在 Pandas.DataFrame 的单元格中

scala - 如何为 Spark 数据帧编写多个 WHEN 条件?