Plotly-Dash: 我怎样才能制作一个仍然显示原始列名的交叉表数据框?

Plotly-Dash: How can I make a dataframe with crosstab that still shows the original column names?

我有以下代码:

df = pd.DataFrame(np.array([["good", "good"], ["bad", "perfect"], ["perfect", "good"], ["perfect", "good"]]), columns=['after', 'before'])
a = np.unique(df.to_numpy())
df = pd.crosstab(df['before'], df['after']).reindex(columns=a, index=a, fill_value=0)
print (df)
after    bad  good  perfect
before                     
bad        0     0        0
good       0     2        1
perfect    1     1        0

当我像这样打印 df 时,会出现 headers“之前”和“之后”。但是,当我不打印而只查看 df 时,这些就会消失。

我想将此数据框转换为以与打印 df 相同的方式显示的破折号数据表。到目前为止,我设法创建的所有数据表的格式与我查看 df 时的格式相同,而不是打印时的格式。我希望我的问题很清楚。

有人知道我该怎么做吗?

提前致谢。

元素 afterbefore 被忽略的原因似乎是它们是 multi-index 的一部分,实际上是索引和列的名称,可检索分别为 df.index.namedf.columns.name。如果你 运行 df.reset_index() 你会得到这个:

after   before  bad good    perfect
0       bad     0   0       0
1       good    0   1       2
2       perfect 1   0       

这很接近您想要的,但不完全是。保留所需信息并使 table 看起来不错的一种方法是在重置索引之前检索 df.index.namedf.columns.name,然后将第一列重命名为 before / after 使用df.rename(columns={df.columns[0]: iname + ' / ' + cname}, inplace=True).

结果如下:

JupyterDash 的完整代码:

import dash
import dash_table
import pandas as pd
from jupyter_dash import JupyterDash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output


# data
#df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/solar.csv')

df = pd.DataFrame(np.array([["good", "good"], ["bad", "perfect"], ["perfect", "good"], ["perfect", "good"]]), columns=['after', 'before'])
a = np.unique(df.to_numpy())
df = pd.crosstab(df['before'], df['after']).reindex(columns=a, index=a, fill_value=0)#.reset_index()

#df = df.reset_index(level=['after', 'before'])
iname = df.index.name
cname = df.columns.name
df = df.reset_index()
df.rename(columns={df.columns[0]: iname + ' / ' + cname}, inplace=True)

app = JupyterDash(__name__)

app.layout = dash_table.DataTable(
    id='table',
    columns=[{"name": i, "id": i} for i in df.columns],
    data=df.to_dict('records'),
)

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

app.run_server(mode='inline', port = 8077, dev_tools_ui=True,
          dev_tools_hot_reload =True, threaded=True)

如果 JupyterDash 不是您的菜,只需按照 中的步骤将其变成标准的 dash 应用程序