【问题标题】:How to use styler with an HTML pandas dataframe如何将样式器与 HTML pandas 数据框一起使用
【发布时间】:2021-01-01 17:49:55
【问题描述】:

关注this stack overflow question,我有一个带有图片的df。我想使用pandas styler 为df 设置一些条件格式。但是,为了显示图像,您需要将 pandas df 转换为 HTML df,并且为了设置 df 的样式,您需要将 df 转换为 styler 对象。有没有办法用图像设置数据框的样式?

获取图片

import pandas as pd
from IPython.core.display import HTML

df = pd.DataFrame([['A231', 'Book', 5, 3, 150], 
                   ['M441', 'Magic Staff', 10, 7, 200]],
                   columns = ['Code', 'Name', 'Price', 'Net', 'Sales'])

# your images
images = ['https://vignette.wikia.nocookie.net/2007scape/images/7/7a/Mage%27s_book_detail.png/revision/latest?cb=20180310083825',
          'https://i.pinimg.com/originals/d9/5c/9b/d95c9ba809aa9dd4cb519a225af40f2b.png'] 


df['image'] = images

# convert your links to html tags 
def path_to_image_html(path):
    return '<img src="'+ path + '" width="60" >'

pd.set_option('display.max_colwidth', -1)

HTML(df.to_html(escape=False ,formatters=dict(image=path_to_image_html)))

样式

import seaborn as sns

cm = sns.light_palette("green", as_cmap=True)

s = df.style.background_gradient(cmap=cm)
s

真的希望能够用图片设置数据框的样式,但我似乎无法弄清楚对象类型。任何帮助表示赞赏。谢谢!

【问题讨论】:

    标签: python pandas dataframe pandas-styles


    【解决方案1】:

    你是如此亲密,你只需要拨打format method of the Styler object s.format({"image": path_to_image_html})

    如果你想要来自这个 Styler 对象的 html,只需使用 render 方法:s.format({"image": path_to_image_html}).render()

    【讨论】:

      猜你喜欢
      • 2021-01-25
      • 2019-03-14
      • 1970-01-01
      • 2016-10-03
      • 1970-01-01
      • 2016-10-06
      • 1970-01-01
      • 2019-02-05
      • 2019-01-19
      相关资源
      最近更新 更多