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

如何调整Dash代码以展示Pandas describe输出的mean、std等统计指标?

解决Dash无法显示Pandas describe统计指标的问题

问题根源

Pandas的describe()方法返回的结果中,mean、std、min等统计指标是以行索引形式存在的,而你使用to_dict('records')转换数据时,行索引不会被自动转为表格列,因此Dash表格中无法看到这些指标。

修改方案

关键步骤

  1. 将describe()结果的行索引转为普通列,用reset_index()实现
  2. 给新列重命名,提升可读性
  3. 基于转换后的数据集生成Dash表格

完整修改代码

import pandas as pd
import numpy as np
import random
from dash import Dash, dash_table

# 原数据集生成代码不变
df = pd.DataFrame({'DATE_TIME':pd.date_range('2022-11-01', '2022-11-05 23:00:00',freq='h'),
                   'Line1':[random.uniform(110, 160) for n in range(120)],
                   'Line2':[random.uniform(60, 100) for n in range(120)],
                   'ID':[random.randrange(1, 100) for n in range(120)],
                   'TIMEINTERVAL':[random.randrange(1, 200) for n in range(120)]})

df['VISIT'] = df['DATE_TIME'].dt.day
df['MODE'] = np.select([df['VISIT']==1, df['VISIT'].isin([2,3])], ['New', 'InProgress'], 'Done')

# 转换describe结果:将索引转为列并命名
desc_df = df.describe().reset_index().rename(columns={'index': '统计指标'})

app = Dash(__name__)

app.layout = dash_table.DataTable(
    data=desc_df.to_dict('records'),
    columns=[{'id': c, 'name': c} for c in desc_df.columns],
    # 可选样式优化
    style_cell={'textAlign': 'left'},
    style_header={'backgroundColor': '#f0f0f0', 'fontWeight': 'bold'}
)

if __name__ == '__main__':
    app.run_server(debug=True)

说明

  • reset_index():把原行索引(统计指标名称)转为名为index的列
  • rename(columns={'index': '统计指标'}):将列名改为更直观的名称,避免默认的index
  • 修改后Dash表格会新增一列显示mean、std等统计指标,同时保留原数值列的统计结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 16:20:28