How to insert specific dataframe column(s) into databse?
Question:
I need to insert a dataframe by column or columns into an SQLite database table. Adding fraction of dataframe columns.
VendorID
tpep_pickup_datetime
tpep_dropoff_datetime
passenger_count
1
2020-01-01 00:28:15
2020-01-01 00:33:03
1.0
1
2020-01-01 00:35:39
2020-01-01 00:43:04
1.0
1
2020-01-01 00:47:41
2020-01-01 00:53:52
1.0
1
2020-01-01 00:55:23
2020-01-01 01:00:14
1.0
2
2020-01-01 00:01:58
2020-01-01 00:04:16
1.0
I know how to insert only one column. When i insert multiple columns it’s not working:
crsr = conn.cursor()
sql = "INSERT INTO vendor (VendorID) VALUES (?)"
# extract column and convert to list of single-value tuples
data = [(x,) for x in df['VendorID']]
crsr.executemany(sql, data)
conn.commit()
How to add one or multiple columns from a Pandas dataframe to an SQLite database with for example tpep_pickup_datetime
and tpep_dropoff_datetime
?
Answers:
You do not do it like this at all. You use the Panda’s to_sql feature. For a more detailed answer, you, of course, need to provide a proper question.
I need to insert a dataframe by column or columns into an SQLite database table. Adding fraction of dataframe columns.
VendorID | tpep_pickup_datetime | tpep_dropoff_datetime | passenger_count |
---|---|---|---|
1 | 2020-01-01 00:28:15 | 2020-01-01 00:33:03 | 1.0 |
1 | 2020-01-01 00:35:39 | 2020-01-01 00:43:04 | 1.0 |
1 | 2020-01-01 00:47:41 | 2020-01-01 00:53:52 | 1.0 |
1 | 2020-01-01 00:55:23 | 2020-01-01 01:00:14 | 1.0 |
2 | 2020-01-01 00:01:58 | 2020-01-01 00:04:16 | 1.0 |
I know how to insert only one column. When i insert multiple columns it’s not working:
crsr = conn.cursor()
sql = "INSERT INTO vendor (VendorID) VALUES (?)"
# extract column and convert to list of single-value tuples
data = [(x,) for x in df['VendorID']]
crsr.executemany(sql, data)
conn.commit()
How to add one or multiple columns from a Pandas dataframe to an SQLite database with for example tpep_pickup_datetime
and tpep_dropoff_datetime
?
You do not do it like this at all. You use the Panda’s to_sql feature. For a more detailed answer, you, of course, need to provide a proper question.