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

如何将透视后的Pandas DataFrame转换为hv.Table并在HV Layout中展示?

Hey there, let's get this sorted out for your report! The key issue you're likely hitting is that HoloViews works best with tidy/long-form data, but your pivoted DataFrame is in wide format. Here's a step-by-step solution to create both the table and a companion chart, then combine them for your report:


First, let's recreate and prepare your data

Start by setting up your pivoted DataFrame, then convert it to long-form (this fixes most HoloViews compatibility issues):

import pandas as pd
import holoviews as hv
hv.extension('bokeh')

# Recreate your pivoted DataFrame
data = {
    'Green': [20, 10, 5],
    'Red': [2, 4, 10],
    'Yellow': [10, 0, 4]
}
df_pivoted = pd.DataFrame(data, index=['B1', 'B2', 'B3'])
df_pivoted.index.name = 'Brand'

# Convert to long-form data (HoloViews' preferred format)
df_long = df_pivoted.reset_index().melt(
    id_vars='Brand',
    var_name='Status',
    value_name='Count'
)

1. Create the HoloViews Dataset

Now we can safely create the HV.Dataset without errors:

hv_dataset = hv.Dataset(df_long, kdims=['Brand', 'Status'], vdims=['Count'])

2. Build your matching table

We can pivot the long-form data back to your original wide format for display:

status_table = hv.Table(df_long).to_pivot_table(
    rows='Brand',
    columns='Status',
    values='Count'
).opts(
    width=400,
    height=220,
    title='Status Counts by Brand'
)

3. Create a companion bar chart

A grouped bar chart is perfect for visualizing these categorical counts:

status_chart = hv.Bars(hv_dataset, kdims=['Brand', 'Status'], vdims=['Count']).opts(
    title='Status Distribution by Brand',
    xlabel='Brand',
    ylabel='Count',
    stacked=False,
    legend_position='right',
    width=600,
    height=400,
    color='Status'
)

4. Combine and export for your report

Merge the table and chart into a single layout, then save it as HTML (easy to embed in most reports):

# Combine into a side-by-side layout
report_layout = (status_chart + status_table).opts(
    hv.opts.Layout(shared_axes=False)
)

# Export to HTML
hv.save(report_layout, 'brand_status_report.html')

Why this works

  • Converting to long-form data aligns with HoloViews' data model, eliminating the errors you encountered with the pivoted wide-format DataFrame.
  • The to_pivot_table method lets you display the data in your original preferred structure while using long-form data under the hood for both visualization and table rendering.

If you had specific error messages (like dimension mismatches), this approach should resolve them by explicitly defining the key and value dimensions for the HoloViews Dataset.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 18:42:39