Search code examples
pythonhtmlpandasdataframedatatables

How to create this dataframe using Pandas?


Please see this -

I want to create a table similar to this using pandas in python? Can anyone guide? Unable to understand how to add "Total Marks" text corresponding to two columns ("Student id" & "Course id").

Thanks


Solution

  • As far as I'm aware, pandas doesn't really support merged cells/cells spanning multiple rows in the same way as Excel/HTML do. A pandas-esque way to include the total row for a single column would be something like the following:

    import pandas as pd
    
    columns = ['Student ID', 'Course ID', 'Marks']
    data = [(103, 201, 67), (103, 203, 67), (103, 204, 89)]
    df = pd.DataFrame(data, columns=columns)
    df.at['Total marks', 'Marks'] = df['Marks'].sum()
    
    print(df)
    

    (per this answer)

    This gives you:

                    Student ID  Course ID  Marks
    0                    103.0      201.0   67.0
    1                    103.0      203.0   67.0
    2                    103.0      204.0   89.0
    Total marks            NaN        NaN  223.0
    

    For HTML output like the image you provided, it looks like you would have to edit the HTML after exporting from pandas (this thread talks about columns but I believe the same applies for merging cells in rows).