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

如何更新Pandas DataFrame列数据及为基因创建分组条形图子图

问题1:如何替换或更新Pandas DataFrame中的列

以下是几种常用方法:

  • 直接赋值:若新数据长度与列匹配,直接覆盖原有列,支持列表、Series、numpy数组等类型:
    import pandas as pd
    df = pd.DataFrame({'A': [1,2,3], 'B': [4,5,6]})
    # 用列表替换B列
    df['B'] = [7,8,9]
    # 用Series替换,需保证索引匹配
    df['B'] = pd.Series([10,11,12], index=df.index)
    
  • update()方法:仅更新索引匹配的位置,缺失索引的新数据不会填充到DataFrame:
    update_series = pd.Series([100, 200], index=[0,2])
    df['A'].update(update_series)
    # 结果A列变为 [100, 2, 200]
    
  • loc精准替换:指定行和列位置进行局部替换:
    # 替换A列中索引0、1的行
    df.loc[[0,1], 'A'] = [99, 88]
    
  • 新增/覆盖列:若列不存在则自动创建,存在则直接覆盖:
    df['C'] = [1,2,3] # 新增C列
    df['C'] = [4,5,6] # 替换C列
    
问题2:修复Plotly分组条形图错误并实现需求

错误原因

代码中for exp in treatment_df遍历的是DataFrame的列名字符串,将字符串传给go.Bar的y参数,而y要求传入数值型数组/Series,因此触发类型错误。

实现代码

import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots

# 从列名提取时间点和患者ID,构建多级列索引
treatment_df.columns = pd.MultiIndex.from_tuples(
    [(col.split('_')[0], col.split('_')[1]) for col in treatment_df.columns],
    names=['时间点', '患者ID']
)

# 重塑数据结构:基因作为分组依据,每条记录对应一个基因-时间点-患者ID的表达值
df_long = treatment_df.T.unstack().reset_index()
df_long.columns = ['基因', '时间点', '患者ID', '表达值']

# 获取所有唯一基因
unique_genes = df_long['基因'].unique()

# 创建子图,每个基因对应一个子图
fig = make_subplots(
    rows=len(unique_genes),
    cols=1,
    subplot_titles=unique_genes,
    vertical_spacing=0.1
)

# 遍历每个基因生成子图
for row_idx, gene in enumerate(unique_genes, start=1):
    gene_data = df_long[df_long['基因'] == gene]
    unique_patients = gene_data['患者ID'].unique()
    
    # 为每个患者添加分组条形
    for patient in unique_patients:
        patient_exp = gene_data[gene_data['患者ID'] == patient]
        fig.add_trace(
            go.Bar(
                name=patient,
                x=patient_exp['时间点'],
                y=patient_exp['表达值']
            ),
            row=row_idx,
            col=1
        )

# 更新图表布局
fig.update_layout(
    height=300 * len(unique_genes),
    title_text="各基因表达值分组条形图",
    barmode='group',
    showlegend=True
)
fig.update_yaxes(title_text="表达值")
fig.update_xaxes(title_text="时间点")
fig.show()

代码说明

  1. 数据重塑:通过多级索引和转置,将宽表转为长表,方便按基因、时间点、患者ID分组;
  2. 子图创建:用make_subplots生成对应基因数量的子图,每个子图对应一个基因的表达情况;
  3. 分组条形:设置barmode='group'实现同一时间点下不同患者的条形分组展示,符合需求中的可视化效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 05:06:34