[英]How to center align headers and values in a dataframe, and how to drop the index in a dataframe
I have the following dataframe:我有以下 dataframe:
import pandas as pd
df = pd.DataFrame({'text': ['foo foo', 'bar bar'],
'number': [1, 2]})
df
How do I center-align both the column titles/headers and the values in a dataframe, and how do I drop the index (the column with the values 0 and 1) in a dataframe?如何将 dataframe 中的列标题/标题和值居中对齐,以及如何在 dataframe 中删除索引(值为 0 和 1 的列)?
Found an answer for this.找到了答案。 This should do the trick to center-align both headers and values and hiding the index:
这应该可以使标题和值居中对齐并隐藏索引:
df1 = df.style.set_table_styles([dict(selector='th', props=[('text-align', 'center')])])
df1.set_properties(**{'text-align': 'center'}).hide_index()
Just to clarify the objective - what you want is to modify the display of the dataframe, not the dataframe itself.只是为了澄清目标-您想要的是修改 dataframe 的显示,而不是 dataframe 本身。 Of course, in the context of Jupyter, you may not care about the distinction - for example, if the only point of having the dataframe is to display it - but it's helpful to distinguish these things so you can use the right tools for the right thing.
当然,在 Jupyter 的上下文中,您可能不关心区别 - 例如,如果拥有 dataframe 的唯一目的是显示它 - 但区分这些东西很有帮助,因此您可以使用正确的工具事物。
In this case, as you've discovered, the styler gives you control over most aspects of the display of the dataframe - it does that by outputting and rendering html.在这种情况下,正如您所发现的,样式器可让您控制 dataframe 显示的大部分方面 - 它通过输出和渲染 html 来实现。
So if your dataframe 'looks' like this in Jupyter:因此,如果您的 dataframe 在 Jupyter 中“看起来”像这样:
But you want it to look more like this:但是您希望它看起来更像这样:
you can use the styler to apply any number of styles (you chain them), so that styled HTML is rendered.您可以使用样式器应用任意数量的 styles(链接它们),以便呈现样式化的 HTML。
df.style.set_table_styles([dict(selector='th', props=[('text-align', 'center')])])\
.hide(axis='index')
In Jupyter this will display as I've shown above, but if you wanted to display this elsewhere and wanted the underlying HTML (let's say you're rendering a page in Flask based on this), you can use the.to_html() method, like so:在 Jupyter 中,这将显示如上所示,但如果您想在其他地方显示它并想要底层 HTML(假设您正在基于此在 Flask 中呈现页面),您可以使用 .to_html() 方法,像这样:
There are two essential advantages to working in this way:以这种方式工作有两个基本优势:
In the context of Jupyter and numbers, this is particularly helpful because you don't have to modify the numbers (eg with rounding or string conversion), you just apply a style format and avoid exponential notation when you don't want it.在 Jupyter 和数字的上下文中,这特别有用,因为您不必修改数字(例如使用舍入或字符串转换),您只需应用样式格式并在不需要时避免使用指数符号。
Here's a modified example, which shows how easy it is to use the styler to 'fix' the Jupyter Pandas numeric display problem:这是一个修改后的示例,它显示了使用样式器“修复”Jupyter Pandas 数字显示问题是多么容易:
df.style.set_properties(subset=["Feature", "Value"], **{'text-align': 'center'})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.