Python 创建表格并另存为 CSV 并显示第一行内容

Python Create Tables and save as CSV and show 1st row contents

我有这个功能代码:

def make_dash_table(df):
    table = []
    for index, row in df.iterrows():
        html_row = []
        for i in range(len(row)):
            html_row.append(html.Td([row[i]]))
        table.append(html.Tr(html_row))
    return table

为 Dash Framework (Python) 创建了一个 table,但是当我在 Python.部分表格自定义显示字幕如下:

modifed_perf_table.insert(
    0, html.Tr([
        html.Td([]),
        html.Td(['Cumulative'], colSpan=4, style={'text-align': "center"}),
        html.Td(['Annualised'], colSpan=4, style={'text-align': "center"})
    ], style={'background': 'white', 'font-weight': '600'}
    )
)

但我想让 table 显示 csv headers(第一行)。 我需要更改的地方:在此代码上或 CSS?

完整代码如下:

df_perf_summary = pd.read_csv('17530.csv', encoding='latin-1')
df_perf_summary.head()

def make_dash_table(df):

    table = []
    for index, row in df.iterrows():
        html_row = []
        for i in range(len(row)):
            html_row.append(html.Td([row[i]]))
        table.append(html.Tr(html_row))
    return table


modifed_perf_table = make_dash_table(df_perf_summary)


modifed_perf_table.insert(
    0, html.Tr([
        html.Td([]),
        html.Td(['Cumulative'], colSpan=4, style={'text-align': "center"}),
        html.Td(['Annualised'], colSpan=4, style={'text-align': "center"})
    ], style={'background': 'white', 'font-weight': '600'}
    )
)

 html.Div([

            html.Div([

            html.Div([
                html.H6("#####",
                        className="gs-header gs-table-header padded"),
                html.Table(modifed_perf_table, className="reversed"),

            ], className="eight columns"),

        ], className="row "),

external_css = ["https://cdnjs.cloudflare.com/ajax/libs/normalize/7.0.0/normalize.min.css",
            "https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css",
            "//fonts.googleapis.com/css?family=Raleway:400,300,600",
            "https://cdn.rawgit.com/plotly/dash-app-stylesheets/5047eb29e4afe01b45b27b1d2f7deda2a942311a/goldman-sachs-report.css",
            "https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"]

csv如下,保存为17530.csv

Col1,Since Launch,,March,April,May,1st Y,2nd Y,3rd Y
,Cum (#),Cum (%),Q2Y18,Q3Y18,Q4Y18,1stYJun19,2ndYJun20,3rdYJun2021
SiteA,15.96,,0.1,0.27,0.27,0.87,0.51,0.43
SiteB,20.09,,0.06,0.21,0.21,2.24,'-1.48,1.46
SiteC,15.7,,'-0.03,'-0.09,'-0.09,'-0.32,'-0.09,0.04

make_dash_table 函数不打印列标签,因为列标签不包含在 DataFrame 对象的行中。可以通过 DataFrame.columns 成员访问列标签,该成员通常是 Series 的 python 字符串。要将它们添加为 HTML table 中的第一行,请在遍历行之前处理它们:

def make_dash_table(df):
    html_row = [html.Td([col]) for col in df.columns]
    table = [html.Tr(html_row)]
    for index, row in df.iterrows():
        html_row = []
        for i in range(len(row)):
            html_row.append(html.Td([row[i]]))
        table.append(html.Tr(html_row))
    return table