[英]How to add column delimiter to Pandas dataframe display
For example, define例如,定义
df=pd.DataFrame(np.random.randint(0,10,(6,6)))
df
Which gives below display in Jupyter notebook这在 Jupyter 笔记本中给出了以下显示
My question is that is it possible to add a column delimiter to the dataframe like我的问题是是否可以向数据框添加列分隔符,例如
Thank you for all the answers, currently I use below custom functions感谢您的所有答案,目前我使用以下自定义函数
def css_border(x,pos):
return ["border-left: 1px solid red" if i in pos else "border: 0px" for i, col in enumerate(x)]
def display_df_with_delimiter(df,pos):
return df.style.apply(partial(css_border,pos=pos), axis=1)
and和
display_df_with_delimiter(df,[0,1,2,5])
gives给
This piece of code should add the desired lines to the table.这段代码应该将所需的行添加到表中。
from IPython.display import display, HTML
CSS = """
.rendered_html td:nth-child(even) {
border-left: 1px solid red;
}
"""
HTML('<style>{}</style>'.format(CSS))
Note that you can change the style of those linse by simply changing the definition of border-left
attribute, ie border-left: 2px solid green
to make the lines thicker and green.请注意,您可以通过简单地更改
border-left
属性的定义来更改那些 linse 的样式,即border-left: 2px solid green
使线条更粗更绿。
Here is a snapshot demonstrating the output.这是演示输出的快照。
Try with pandas.style.apply(...)
:尝试使用
pandas.style.apply(...)
:
from IPython.core.display import display, HTML
def css_border(x):
return ["border-left: 1px solid red" if (i%2==0) else "border: 0px" for i, col in enumerate(x)]
html = (
df.style.apply(css_border, axis=1).render()
)
display(HTML(html))
Usually, we do this:通常,我们这样做:
df[[0,1,2,3]]
and it will print columns 0 to 3 - if you want columns 0-1 and 2-3 printed separately:它将打印第 0 到 3 列 - 如果您想分别打印第 0-1 和 2-3 列:
from IPython.display import display, HTML
CSS = """
.output {
flex-direction: row;
}
"""
HTML('<style>{}</style>'.format(CSS))
and then call display for dataframe as:然后调用数据帧的显示为:
display(df[[0,1]])
display(df[[2,3]])
Let me know if this helps!让我知道这是否有帮助!
UPDATE: Add lines in CSS as follows:
更新:在 CSS 中添加行如下:
CSS = """
.rendered_html td:nth-last-child(2n) {
border-right: 1px solid red;
}
"""
It adds red lines for every 2nd column - ofcourse you can edit the number of 'n' here as you like.它为每第二列添加红线 - 当然,您可以根据需要在此处编辑“n”的数量。
Hope this helps!希望这可以帮助!
UPDATE: UPDATE: for every n-value CSS:
更新:更新:对于每个 n 值 CSS:
def delimit_views(delimiters):
output = str()
for delim in delimiters:
output += ".rendered_html td:nth-child("+str(delim)+") {
border-left: 1px solid red;}"
return output
And now append this CSS to the HTML for your display.现在将此 CSS 附加到 HTML 以供显示。
Hope it works this time!希望这次能成功!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.