How to Convert List to Table in Python

Here is the logic to convertĀ list to a table in Python. The code in this topic will do two things writing list data to a dataframe and saving it to a database table. From the table, you can query and get insights.

In two steps you can do. The step one is write list data to dataframe. From dataframe you can write it to a table for future analysis.

Writing data to dataframe

In the first statement, you imported the Pandas library. There are two lists – names and grades. Then the zip function compress these two lists. The df objects contain the dataframe.

import pandas as pd
names = ['Bob','Jessica','Mary','John','Mel']
grades = [76,95,77,78,99]
GradeList = zip(names,grades)
df = pd.DataFrame(data = GradeList,
    columns=['Names', 'Grades'])
df
Advertisements

Export (save) the data to Table

Here you imported the sqlite3 database. The con object connects to the database. Here mydb.db. Next, the df. to_sql exports data to the SQLite table. Below is the self-explanatory syntax. The logic is helpful for data-analytics engineers.

import os
import sqlite3 as lite
db_filename = r'mydb.db'
con = lite.connect(db_filename)
df.to_sql('mytable',
    con,
    flavor='sqlite',
    schema=None,
    if_exists='replace',
index=True,
index_label=None,
chunksize=None,
dtype=None)
con.close()

Once data exports to SQL Table, you can query it to get meaningful insights.

Related

References

Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.