Create a SQLite database from only certain columns of a pandas df?

Viewed 342

I know how to use to_sql.() to copy all data from a pandas data-frame to a table in a sqlite database, but how do I create a table in a sqlite database using only certain, selected columns from the pandas data-frame?

TIA.

2 Answers
cols = ['your', 'desired', 'database', 'columns']

df[cols].to_sql()

You can create a list of columns, and then take only those columns while calling to_sql Something like:

>>df
   a  b  stats
0  1  A      0
1  2  B      1
2  3  C      0
>>import sqlite3
>>conn = sqlite3.connect('test.db')
>>cols = ['a', 'stats']
>>df[cols].to_sql('newTable', conn)

SQLite Output:

enter image description here

Related