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

绘制基因表达随时间变化散点图时遇ValueError报错求助

问题

需要为每个基因绘制时间(x轴)对基因表达量(y轴)的散点图,但运行代码时触发ValueError: DataFrame constructor not properly called!错误。

运行代码

import plotly.express as px
import numpy as np
import pandas as pd

for time, gene_expr in df5.iloc[:, 1:-1].iterrows():
  X = time
  y = gene_expr

  fig = px.scatter(X, y)
  fig.show()

报错回溯

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-424-e9af712893e6> in <module>()
      4   y = gene_expr
      5 
----> 6   fig = px.scatter(X, y)
      7   fig.show()

3 frames
/usr/local/lib/python3.7/dist-packages/plotly/express/_chart_types.py in scatter(data_frame, x, y, color, symbol, size, hover_name, hover_data, custom_data, text, facet_row, facet_col, facet_col_wrap, facet_row_spacing, facet_col_spacing, error_x, error_x_minus, error_y, error_y_minus, animation_frame, animation_group, category_orders, labels, orientation, color_discrete_sequence, color_discrete_map, color_continuous_scale, range_color, color_continuous_midpoint, symbol_sequence, symbol_map, opacity, size_max, marginal_x, marginal_y, trendline, trendline_options, trendline_color_override, trendline_scope, log_x, log_y, range_x, range_y, render_mode, title, template, width, height)
     64     mark in 2D space.
     65     """
---> 66     return make_figure(args=locals(), constructor=go.Scatter)
     67 
     68 

/usr/local/lib/python3.7/dist-packages/plotly/express/_core.py in make_figure(args, constructor, trace_patch, layout_patch)
   1943     apply_default_cascade(args)
   1944 
-> 1945     args = build_dataframe(args, constructor)
   1946     if constructor in [go.Treemap, go.Sunburst, go.Icicle] and args["path"] is not None:
   1947         args = process_dataframe_hierarchy(args)

/usr/local/lib/python3.7/dist-packages/plotly/express/_core.py in build_dataframe(args, constructor)
   1304     df_provided = args["data_frame"] is not None
   1305     if df_provided and not isinstance(args["data_frame"], pd.DataFrame):
-> 1306         args["data_frame"] = pd.DataFrame(args["data_frame"])
   1307     df_input = args["data_frame"]
   1308 

/usr/local/lib/python3.7/dist-packages/pandas/core/frame.py in __init__(self, data, index, columns, dtype, copy)
    728         else:
    729             if index is None or columns is None:
-> 730                 raise ValueError("DataFrame constructor not properly called!")
    731 
    732             # Argument 1 to "ensure_index" has incompatible type "Collection[Any]";

ValueError: DataFrame constructor not properly called!

数据示例(df5.head().to_dict())

{'DNAJA1': {'0': 0.28248390645176796,
  '12': 0.27744322221439516,
  '24': 0.210254923999168,
  '4': 0.25179129535390465,
  '8': 0.23958153803449567},
 ...
 'survival_info': {'0': '0h', '12': '12h', '24': '24h', '4': '4h', '8': '8h'}}

环境版本

  • Python 3.7.13
  • Plotly 5.9.0
  • Pandas 1.3.5

解决方案

问题根源

  1. 遍历方向错误:你的数据结构是列对应基因,行对应时间点,但代码用iterrows()遍历行,拿到的是行索引和整行基因数据,完全不符合「每个基因对应所有时间点表达量」的需求。
  2. Plotly参数格式错误:px.scatter()单独传x和y时,Plotly会默认把第一个参数当作data_frame处理,而你传的是单个行索引值,无法构造DataFrame,直接触发报错。

修复代码

import plotly.express as px
import pandas as pd

# 提取时间信息(从survival_info列)
time_values = df5['survival_info']

# 遍历每个基因列(排除首尾无关列)
for gene_name in df5.columns[1:-1]:
    # 构造当前基因的专属DataFrame:时间+表达量
    gene_df = pd.DataFrame({
        '时间': time_values,
        '基因表达量': df5[gene_name]
    })
    # 绘制散点图并添加基因标题
    fig = px.scatter(gene_df, x='时间', y='基因表达量', title=f'基因{gene_name} 时间-表达量散点图')
    fig.show()

备选方案(用行索引当时间)

如果你的行索引本身就是时间数值(比如示例中的'0'、'12'),可以直接用行索引生成时间标签:

for gene_name in df5.columns[1:-1]:
    gene_df = pd.DataFrame({
        '时间': df5.index.astype(str) + 'h',
        '基因表达量': df5[gene_name]
    })
    fig = px.scatter(gene_df, x='时间', y='基因表达量', title=f'基因{gene_name} 时间-表达量散点图')
    fig.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 13:54:38