数据可视化是数据分析和机器学习的关键方面。 Gradio DataFrame 组件是一种在 Web 应用程序中显示表格数据的常用方式。
但是,如果您想美化数据表怎么办? 如果您想添加背景颜色、部分突出显示单元格或更改数字的显示精度怎么办? 本指南就是为您准备的!
让我们开始吧!
先决条件:我们将在示例中使用 gradio.Blocks 类。 如果您不熟悉它,可以先阅读 Blocks 指南。 另外请确保您使用的是 最新版本 的 Gradio:pip install --upgrade gradio。
StylerGradio DataFrame 组件现在支持来自 pandas 类的 Styler 类型的值。 这使我们能够重用 Styler 类丰富的现有 API 和文档,而不是自行发明新的样式格式。 这是一个完整的示例
import pandas as pd
import gradio as gr
# Creating a sample dataframe
df = pd.DataFrame({
"A" : [14, 4, 5, 4, 1],
"B" : [5, 2, 54, 3, 2],
"C" : [20, 20, 7, 3, 8],
"D" : [14, 3, 6, 2, 6],
"E" : [23, 45, 64, 32, 23]
})
# Applying style to highlight the maximum value in each row
styler = df.style.highlight_max(color = 'lightgreen', axis = 0)
# Displaying the styled dataframe in Gradio
with gr.Blocks() as demo:
gr.DataFrame(styler)
demo.launch()Styler 类可用于对数据框应用条件格式和样式,使其更具视觉吸引力且更易于理解。 您可以突出显示某些值、应用渐变,甚至使用自定义 CSS 来设置 DataFrame 的样式。 Styler 对象应用于 DataFrame,并返回具有相关样式属性的新对象,然后可以直接预览,或在 Gradio 界面中动态渲染。
要了解有关 Styler 对象的更多信息,请阅读官方 pandas 文档:https://pandas.ac.cn/docs/user_guide/style.html
下面,我们将探讨几个示例
好的,让我们重新回顾一下前面的示例。 我们首先创建一个 pd.DataFrame 对象,然后用浅绿色突出显示每行中的最大值
import pandas as pd
# Creating a sample dataframe
df = pd.DataFrame({
"A" : [14, 4, 5, 4, 1],
"B" : [5, 2, 54, 3, 2],
"C" : [20, 20, 7, 3, 8],
"D" : [14, 3, 6, 2, 6],
"E" : [23, 45, 64, 32, 23]
})
# Applying style to highlight the maximum value in each row
styler = df.style.highlight_max(color = 'lightgreen', axis = 0)现在,我们只需将此对象传递给 Gradio DataFrame,即可在 4 行 python 代码中可视化我们色彩斑斓的数据表
import gradio as gr
with gr.Blocks() as demo:
gr.Dataframe(styler)
demo.launch()效果如下

除了突出显示单元格之外,您可能还希望为单元格中的特定文本着色。 以下是更改某些列文本颜色的方法
import pandas as pd
import gradio as gr
# Creating a sample dataframe
df = pd.DataFrame({
"A" : [14, 4, 5, 4, 1],
"B" : [5, 2, 54, 3, 2],
"C" : [20, 20, 7, 3, 8],
"D" : [14, 3, 6, 2, 6],
"E" : [23, 45, 64, 32, 23]
})
# Function to apply text color
def highlight_cols(x):
df = x.copy()
df.loc[:, :] = 'color: purple'
df[['B', 'C', 'E']] = 'color: green'
return df
# Applying the style function
s = df.style.apply(highlight_cols, axis = None)
# Displaying the styled dataframe in Gradio
with gr.Blocks() as demo:
gr.DataFrame(s)
demo.launch()在此脚本中,我们定义了一个自定义函数 highlight_cols,它将所有单元格的文本颜色更改为紫色,但对于 B、C 和 E 列则覆盖为绿色。 效果如下

有时,您处理的数据可能包含很长的浮点数,您可能希望为了简单起见只显示固定位数的小数。 pandas Styler 对象允许您格式化显示的数字精度。 您可以这样做
import pandas as pd
import gradio as gr
# Creating a sample dataframe with floating numbers
df = pd.DataFrame({
"A" : [14.12345, 4.23456, 5.34567, 4.45678, 1.56789],
"B" : [5.67891, 2.78912, 54.89123, 3.91234, 2.12345],
# ... other columns
})
# Setting the precision of numbers to 2 decimal places
s = df.style.format("{:.2f}")
# Displaying the styled dataframe in Gradio
with gr.Blocks() as demo:
gr.DataFrame(s)
demo.launch()在此脚本中,Styler 对象的 format 方法用于将数字精度设置为小数点后两位。 现在干净多了

到目前为止,我们一直局限于 Pandas Styler 类支持的样式。 但是,如果您想创建自定义样式(例如根据值部分突出显示单元格)怎么办

使用 Styler 无法实现这一点,但您可以通过创建自己的 styling 数组来实现,该数组是一个与您的数据大小和形状相同的 2D 数组。 此列表中的每个元素都应该是一个 CSS 样式字符串(例如 "background-color: green"),它适用于包含单元格值的 <td> 元素(如果不需要应用自定义 CSS,则为空字符串)。 同样,您可以创建 display_value 数组来控制每个单元格中显示的值(这可能与用于搜索/排序的基础值不同)。
以下是如何使用 gr.Dataframe 应用自定义样式的完整代码,如上面的屏幕截图所示
import gradio as gr
data = [
["DeepSeek Coder", 79.3],
["Llama 3.3", 68.9],
["Qwen 2.5", 61.9],
["Gemma 2", 59.5],
["GPT 2", 18.3],
]
headers = ["Model", "% Correct (LeetCode Hard)"]
def get_styling(values):
return [["", f"background: linear-gradient(90deg, rgba(220, 242, 220) {row[1]}%, transparent {row[1]}%)"] for row in values]
def get_display_value(values):
display_values = []
medals = ["🥇", "🥈", "🥉"]
for i, row in enumerate(values):
if i < 3:
display_values.append([f"{medals[i]} {row[0]}", row[1]])
else:
display_values.append([row[0], row[1]])
return display_values
styling = get_styling(data)
display_value = get_display_value(data)
value = {
"data": data,
"headers": headers,
"metadata": {
"styling": styling,
"display_value": display_value,
},
}
with gr.Blocks() as demo:
gr.Dataframe(value, show_search="search")
demo.launch()
需要记住的一件事是,gradio DataFrame 组件只有在非交互模式(即“静态”模式)下才接受自定义样式对象。 如果 DataFrame 组件是交互式的,则样式信息将被忽略,并显示原始表格值。
DataFrame 组件默认是非交互式的,除非它被用作事件的输入。 在这种情况下,您可以通过设置 interactive 属性来强制组件非交互式,如下所示
c = gr.DataFrame(styler, interactive=False)这只是使用 gradio.DataFrame 组件和来自 pandas 的 Styler 类可以实现的功能的一小部分。 试一试,让我们知道您的想法!