【问题标题】:how to hide index 0 of PANDAS and Jupyter如何隐藏 PANDAS 和 Jupyter 的索引 0
【发布时间】:2017-12-03 22:44:09
【问题描述】:

我想从我的 jupyter 笔记本中隐藏 de index 0(行):

display(df.style.set_properties(**{'text-align': 'left'})

我使用的方法是样式,以便将其作为 html 并左对齐, 其中 df 是一个简单的 PANDAS 数据帧。

谢谢!

【问题讨论】:

  • 有什么原因你不能只显示没有第一行的数据框df.loc[1:]

标签: python-3.x pandas jupyter-notebook


【解决方案1】:

目前还不清楚你想要什么。所以我来猜一猜。

考虑数据框df

df = pd.DataFrame([[1, 2], [3, 4], [5, 6]], list('ABC'), list('XY'))

正如@chtonicdaemon 指出的那样,因为简单地“隐藏”第一行非常容易:

df.iloc[1:]

   X  Y
B  3  4
C  5  6

我假设你想要一些不同的东西。我之前看到过的问题是如何不显示索引?我将首先指出我以前的答案ColorChange

这是我将用来应用我自己的css的函数

def HTML_with_style(df, style=None, random_id=None):
    from IPython.display import HTML
    import numpy as np
    import re

    df_html = df.to_html()

    if random_id is None:
        random_id = 'id%d' % np.random.choice(np.arange(1000000))

    if style is None:
        style = """
        <style>
            table#{random_id} {{color: blue}}
        </style>
        """.format(random_id=random_id)
    else:
        new_style = []
        s = re.sub(r'</?style>', '', style).strip()
        for line in s.split('\n'):
                line = line.strip()
                if not re.match(r'^table', line):
                    line = re.sub(r'^', 'table ', line)
                new_style.append(line)
        new_style = ['<style>'] + new_style + ['</style>']

        style = re.sub(r'table(#\S+)?', 'table#%s' % random_id, '\n'.join(new_style))

    df_html = re.sub(r'<table', r'<table id=%s ' % random_id, df_html)

    return HTML(style + df_html)

我会用我自己的css 调用它来抑制索引

style = """
<style>
    table tr :first-child{display: none;}
</style>
"""

HTML_with_style(df, style)


这不适用于print(df)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    相关资源
    最近更新 更多