pandasread-csv

customize header pandas to html


I created a web application to search content in CSV files.for now i only able to put all content into 1 column with comma as delimiter , I want to display the data as shown in the image. My python code

selected_columns = [202, 9, 10, 135, 13, 127, 126, 26, 28,128,129,31,33]
df = df.iloc[:, selected_columns]
df.columns = ['CDRID', 'ANumber', 'To', 'SipStatus', 'ISrcIP', 'IDstIP', 'ISrcRTP', 'IDstRTP', 'OSrcIP', 'ODstIP', 'OSrcRTP', 'ODstRTP']]
df['Ingress'] = df[['ISrcIP', 'IDstIP', 'ISrcRTP', 'IDstRTP']].apply(lambda x: ', '.join(x.dropna().astype(str)), axis=1)
df['Egress'] = df[[ 'OSrcIP', 'ODstIP', 'OSrcRTP', 'ODstRTP']].apply(lambda x: ', '.join(x.dropna().astype(str)), axis=1)
df = df.drop(columns=['ISrcIP', 'IDstIP', 'ISrcRTP', 'IDstRTP', 'OSrcIP', 'ODstIP', 'OSrcRTP', 'ODstRTP'])    
df = df.drop(columns=['ISrcIP', 'IDstIP', 'ISrcRTP', 'IDstRTP', 'OSrcIP', 'ODstIP', 'OSrcRTP', 'ODstRTP'])
combined_df = pd.concat([combined_df, df], ignore_index=True)
results.append(('Combined Results', combined_df.to_html(index=False)))

html frontend code

        {% for file, table in results %}
    <div class="container-fluid">
    <div class="table-responsive">
        <table class="table table-striped table-bordered table-hover">
            {{ table|safe }}
        </table>
    </div>
{% endfor %}

current output Current html output

expected html header
expected output


Solution

  • You can use multi-index to have several levels of column headers and you can use .style.set_table_styles to customize the display of the dataframe:

    cols = ['CDRID', 'ANumber', 'To', 'SipStatus', 'ISrcIP', 'IDstIP', 'ISrcRTP', 'IDstRTP', 
            'OSrcIP', 'ODstIP', 'OSrcRTP', 'ODstRTP']
    df = pd.DataFrame(np.round(100*np.random.random((3, 12))), columns=cols)
    
    # Use multi-index
    df.columns = pd.MultiIndex.from_arrays([4*[""] + 4*["Ingress"] + 4*["Outgress"], df.columns])
    
    # Add borders and hide the index
    df_styled = df.style.set_table_styles([
         {"selector": "td", "props": [("border", "1px solid black")]},  # cells borders
         {"selector": "th", "props": [("border", "1px solid black")]},  # headers borders
         {"selector": "th", "props": [("text-align", "center")]},  # text headers alignment
    ])
    display(df_styled.hide(axis="index"))
    # print(df_styled.to_html())  # to get the HTML/CSS code
    

    df