0

I have looked here but the solution is still not working out for me... I have 2 lists

list1 = ['src_table', 'error_response_code', 'error_count', 'max_dt']

list2 = ['src_periods_43200', 404, 21, datetime.datetime(2020, 5, 26, 21, 10, 7)',
         'src_periods_86400', 404, 19, datetime.datetime(2020, 5, 25, 21, 10, 7)']

The list1 carries the column names of the HTML table.

The second list2 carries the table data.

How do I generate the HTML table out of these 2 lists so that the first list is used for column names and the second as the table data (row-wise)

the result should be:

src_table          |  error_response_code  | error_count  | max_dt                  |
src_periods_43200  |  404                  | 21           | 2020-5-26    21:10:7    |
src_periods_43200  |  404                  | 19           | 2020-5-25    21:10:7    |

many thanks

Shery
  • 1,808
  • 5
  • 27
  • 51

2 Answers2

1

This Should do it

import pandas as pd
import datetime

list1 = ['src_table', 'error_response_code', 'error_count', 'max_dt']

list2 = [
    'src_periods_43200', 404, 21, datetime.datetime(2020, 5, 26, 21, 10, 7),
    'src_periods_86400', 404, 19, datetime.datetime(2020, 5, 25, 21, 10, 7)
]


index_break = len(list1)
if len(list2) % index_break != 0:
    raise Exception('Not enough data.')

staged_list = []
current_list = []

for idx in range(0, len(list2)):
    current_list.append(list2[idx])

    if len(current_list) == index_break:
        staged_list.append(current_list.copy())
        current_list = []

df = pd.DataFrame(data=staged_list, columns=list1)

print(df.to_html())
Supun De Silva
  • 1,437
  • 9
  • 15
  • exactly what I was looking for... thanks... do you know how to add a little bit of formatting? @Supun De Silva – Shery May 28 '20 at 09:10
  • 1
    You can pass a list of css classes to `.to_html()` function as an array. i.e `df.to_html(classes=['my-table-style'])` Ref: https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.DataFrame.to_html.html – Supun De Silva May 28 '20 at 09:23
0

You can easily write your function for that Something like:

import datetime

list1 = ['src_table', 'error_response_code', 'error_count', 'max_dt']

list2 = ['src_periods_43200', 404, 21, datetime.datetime(2020, 5, 26, 21, 10, 7), 'src_periods_86400', 404, 19, datetime.datetime(2020, 5, 25, 21, 10, 7)]

print('<table>')
print('<thead><tr>')
for li in list1:
    print(f'<th>{li}</th>')
print('</tr></thead>')
print('<tbody>')
for i in range(0, int(len(list2)/4)):
    print('<tr>')
    print(f'<td>{list2[4*i+0]}</td>')
    print(f'<td>{list2[4*i+1]}</td>')
    print(f'<td>{list2[4*i+2]}</td>')
    print(f'<td>{list2[4*i+3]}</td>')
    print('</tr>')
print('</tbody>')
print('</table>')