python-3.x - python破折号表条件格式色标

标签 python-3.x plotly-dash

我想根据值从高到小用色标按值对列进行着色
像这样
https://i.imgur.com/GZpIXu1.png
目前,我在一个函数中创建了破折号表,并为每一列循环发送它;

def make_table_in_div(df, column_name):
    pv = pd.pivot_table(df, index=[column_name], values=['val1'], aggfunc=['mean', 'count']).reset_index()
    pv.columns = [column_name, 'val1', 'count']
    print(column_name)
    div = html.Div([html.H1(column_name), dash_table.DataTable(
        columns=[{"name": i, "id": i} for i in pv.columns],
        data=pv.to_dict('records'),
    )], style={'height': 30, 'margin-right': 'auto', 'margin-left': 'auto', 'width': '800px'})  # 'width': '50%',
    return div

div = [make_table_in_div(df, column_name) for column_name in ['column_name']]
return div
破折号表看起来像流动的图片,我想给值列着色
enter image description here

最佳答案

感谢 The answer of Kristian Haga . - 效果很好。
我想为将来有同样问题的用户和我总结一下选项。当我们想在多列上运行它时,有两种选择:

  • 原始函数将以相同的比例(最小值和最大值)为所有列着色,因此如果我运行多列(来自示例:值和计数),它会返回基于所有列的最小值和最大值范围着色的表格样式(来自示例:0.193,109)。discrete_background_color_bins(df, columns=['value','count']) https://i.imgur.com/bDrd8q1.png
    def discrete_background_color_bins(df, n_bins=7, columns='all'):
    
     bounds = [i * (1.0 / n_bins) for i in range(n_bins+1)]
     if columns == 'all':
         if 'id' in df:
             df_numeric_columns = df.select_dtypes('number').drop(['id'], axis=1)
         else:
             df_numeric_columns = df.select_dtypes('number')
     else:
         df_numeric_columns = df[columns]
     df_max = df_numeric_columns.max().max()
     df_min = df_numeric_columns.min().min()
     ranges = [
         ((df_max - df_min) * i) + df_min
         for i in bounds
     ]
     styles = []
     legend = []
     for i in range(1, len(bounds)):
         min_bound = ranges[i - 1]
         max_bound = ranges[i]
         backgroundColor = colorlover.scales[str(n_bins+4)]['div']['RdYlGn'][2:-2][i - 1]
         color = 'black'
    
         for column in df_numeric_columns:
             styles.append({
                 'if': {
                     'filter_query': (
                         '{{{column}}} >= {min_bound}' +
                         (' && {{{column}}} < {max_bound}' if (i < len(bounds) - 1) else '')
                     ).format(column=column, min_bound=min_bound, max_bound=max_bound),
                     'column_id': column
                 },
                 'backgroundColor': backgroundColor,
                 'color': color
             })
         legend.append(
             html.Div(style={'display': 'inline-block', 'width': '60px'}, children=[
                 html.Div(
                     style={
                         'backgroundColor': backgroundColor,
                         'borderLeft': '1px rgb(50, 50, 50) solid',
                         'height': '10px'
                     }
                 ),
                 html.Small(round(min_bound, 2), style={'paddingLeft': '2px'})
             ])
         )
    
     return (styles, html.Div(legend, style={'padding': '5px 0 5px 0'}))
    
  • 如果我们想根据其最小值和最大值分别为每一列着色,
    enter image description here
    我们将使用下面的函数:
    (非常相似,但首先在列上运行)
     def discrete_background_color_bins(df, n_bins=7, columns='all'):
    
         bounds = [i * (1.0 / n_bins) for i in range(n_bins+1)]
         if columns == 'all':
             if 'id' in df:
                 df_numeric_columns = df.select_dtypes('number').drop(['id'], axis=1)
             else:
                 df_numeric_columns = df.select_dtypes('number')
         else:
             df_numeric_columns = df[columns]
         df_max = df_numeric_columns.max().max()
         df_min = df_numeric_columns.min().min()
         ranges = [
             ((df_max - df_min) * i) + df_min
             for i in bounds
         ]
         styles = []
         legend = []
         for i in range(1, len(bounds)):
             min_bound = ranges[i - 1]
             max_bound = ranges[i]
             backgroundColor = colorlover.scales[str(n_bins+4)]['div']['RdYlGn'][2:-2][i - 1]
             color = 'black'
    
             for column in df_numeric_columns:
                 styles.append({
                     'if': {
                         'filter_query': (
                             '{{{column}}} >= {min_bound}' +
                             (' && {{{column}}} < {max_bound}' if (i < len(bounds) - 1) else '')
                         ).format(column=column, min_bound=min_bound, max_bound=max_bound),
                         'column_id': column
                     },
                     'backgroundColor': backgroundColor,
                     'color': color
                 })
             legend.append(
                 html.Div(style={'display': 'inline-block', 'width': '60px'}, children=[
                     html.Div(
                         style={
                             'backgroundColor': backgroundColor,
                             'borderLeft': '1px rgb(50, 50, 50) solid',
                             'height': '10px'
                         }
                     ),
                     html.Small(round(min_bound, 2), style={'paddingLeft': '2px'})
                 ])
             )
    
         return (styles, html.Div(legend, style={'padding': '5px 0 5px 0'}))
    
  • 关于python-3.x - python破折号表条件格式色标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63372283/

    相关文章:

    python - 尝试比较 2 个大文件的行并保留匹配的行,但没有匹配的行

    python - 如何为 Dash/Plotly 中的下拉菜单命名

    python - 如何在破折号应用程序中延迟用户对文本框的输入?

    python - Dash - 间隔不调用回调

    python - 是否可以通过ctypes方便地访问_thread.RLock的计数?

    python - 无法理解此代码片段的输出

    python - 按元组的指定元素对带有元组键的字典进行排序

    python - 部署 Dash 应用程序时出现 Heroku 应用程序错误

    docker - 在 Nginx、Gunicorn、Flask 和 Docker 下运行多个 Dash 应用

    python - paramiko ls 有几个文件输出被截断