You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在pandas dataframe列中插入可正常渲染的checkbox复选框

问题原因

pandas 默认渲染DataFrame时会调用单元格对象的__repr__方法转换为文本,因此直接存入ipywidget对象只会显示类的文本描述,不会渲染为可交互组件。


解决方案1:纯前端可勾选复选框(无需Python端获取状态)

如果只需要前端展示可勾选的复选框,不需要在Python代码中获取选中状态,可以通过渲染HTML实现:

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

# 构建原始DataFrame
data = [['Ankit'], ['Akshat' ]]
df = pd.DataFrame(data, columns = ['Name'])
# 插入PPA列,值为checkbox的HTML标签
df.insert(loc = 0, column = 'PPA', value = '<input type="checkbox">')
# 渲染HTML时禁止转义特殊字符
display(HTML(df.to_html(escape=False)))

解决方案2:可交互复选框(支持Python端获取选中状态)

如果需要在代码中获取用户的勾选状态,需要用ipywidgets手动构建交互表格:

import pandas as pd
import ipywidgets as widgets
from IPython.display import display

# 构建原始DataFrame
data = [['Ankit'], ['Akshat' ]]
df = pd.DataFrame(data, columns = ['Name'])

# 为每行生成独立的checkbox对象
checkbox_list = [widgets.Checkbox(value=False, indent=False, description='') for _ in range(len(df))]

# 构建表格头部
table_header = widgets.HBox([
    widgets.Label('PPA', layout=widgets.Layout(width='40px')),
    widgets.Label('Name', layout=widgets.Layout(width='100px'))
])

# 构建每行内容
table_rows = [table_header]
for checkbox, name in zip(checkbox_list, df['Name']):
    row = widgets.HBox([
        checkbox,
        widgets.Label(name, layout=widgets.Layout(width='100px'))
    ])
    table_rows.append(row)

# 渲染完整表格
full_table = widgets.VBox(table_rows)
display(full_table)

# 后续可通过如下代码获取选中的行数据
# selected = [df['Name'].iloc[i] for i, cb in enumerate(checkbox_list) if cb.value]

内容的提问来源于stack exchange,提问作者ankit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 03:54:04