在传递给Plotly函数之前,如何重塑熊猫数据框?

时间:2020-06-14 02:07:45

标签: pandas plotly plotly-dash plotly-python

我正在尝试使用Table()中的 Plotly 函数创建数据表。

我的数据如下:

import pandas as pd

test_df = pd.DataFrame({'Manufacturer':['Mercedes', 'Buick', 'Ford', 'Buick', 'Buick', 'Ford', 'Buick', 'Chrysler', 'Ford', 'Buick', 'Chrysler', 'Ford', 'Buick', 'Ford', 'Ford', 'Chrysler', 'Chrysler', 'Ford', 'Chrysler', 'Chrysler', 'Chrysler', 'Buick'],
                          'Metric':['MPG', 'Score', 'Score', 'Score', 'Score', 'Score', 'Score', 'Score', 'Score', 'Score', 'Score', 'Score', 'Score', 'Score', 'Score', 'Score', 'Score', 'Score', 'Score', 'Score', 'Score', 'Score'],
                          'Statistic':['External', 'Min', 'Max', 'Average', 'Median', '90th', '95th', '99th', 'Min', 'Max', 'Average', 'Median', '90th', '95th', '99th','Min', 'Max', 'Average', 'Median', '90th', '95th', '99th'],
                          'Value':[22, 3.405, 100.29, 4.62, 4.425, 5.34, 5.83, 7.75, 2.6323, 210, 4.193, 3.28, 5.04, 6.36, 11.01, 3.72, 43, 4.98, 4.82, 5.775, 6.18, 7.182],
                       })

我希望能够创建一个如下表:

Manufacturer    Min      Max      Average      Median      90th      95th      99th
Buick           3.405    210      4.62         4.425       5.04      5.83      7.182
Chrysler        3.72     43       4.193        4.82        5.775     6.18      7.75
Ford            2.6323   100.29   4.98         3.28        5.34      6.36      11.01

执行此操作的代码如下所示(硬编码时):

import plotly.graph_objects as go 
go.Figure(go.Table(
        header=dict(
            values=["Manufacturer", "Min", "Max",
                    "Average", "Median", "90th",
                    "95th", "99th"],
            font=dict(size=10),
            align="left"
        ),
        cells=dict(
            values=[['Buick', 'Ford', 'Chrysler'],    # Headers (could change based on the source file)
                    [3.405, 3.72, 2.6323],            # Min values
                    [210, 43, 100.29],                # Max values
                    [4.62, 4.193, 4.98],              # Average values
                    [4.425, 4.82, 3.28],              # Median values
                    [5.04, 5.775, 5.34],              # 90th percentile values
                    [5.83, 6.18, 6.36],               # 95th percentile values
                    [7.182, 7.75, 11.01]              # 99th percentile values
                   ],
            align = "left")                                     
))

enter image description here

根据https://plotly.com/python/table/上的文档,cells参数参数需要一个列表列表,并且可以采用熊猫数据框(很好!)。

使用文档中的示例,传递熊猫数据框的代码如下所示:

# THIS IS THE EXAMPLE FROM THE DOCS (SHOWING THE USE OF A DATA FRAME)
fig = go.Figure(data=[go.Table(
    header=dict(values=list(df.columns),
                fill_color='paleturquoise',
                align='left'),
    cells=dict(values=[df.Rank, df.State, df.Postal, df.Population],
               fill_color='lavender',
               align='left'))
])

我最英勇的尝试失败了:

仅按“得分”记录过滤:

test_df_subset = test_df[(test_df['Metric'] == 'Score') & (test_df['Manufacturer'].isin(['Buick', 'Ford', 'Chrysler']))]

创建数据透视表:

temp_df = pd.pivot_table(data=test_df_subset,index=['Statistic', 'Manufacturer']) 

拆开数据透视表:

temp_df.unstack(0)

问题:如何重塑test_df数据框,以便将其传递给data函数中的cellsgo.Figure()参数? / strong>

谢谢!

1 个答案:

答案 0 :(得分:1)

你很近,这是一种方法

import plotly.graph_objects as go 

cols_ = ["Manufacturer", "Min", "Max",
         "Average", "Median", "90th",
         "95th", "99th"]
manufacturers = ['Buick', 'Ford', 'Chrysler']

#this is what you are looking for
df_ = (test_df[test_df['Manufacturer'].isin(manufacturers)]
              .set_index(['Manufacturer', 'Statistic'])
               ['Value'].unstack()
               .reset_index()[cols_]
               )

go.Figure(go.Table(
        header=dict(
            values=cols_,
            font=dict(size=10),
            align="left"
        ),
        cells=dict(
            values=df_.T, # note the T here
            align = "left")                                     
))

与您的方法相比,我认为df_(用我的符号表示)等效于temp_df.unstack(0)['Value'].reset_index()[cols_],用您的符号表示,并使用cols_对其进行排序