hangc
hangc

Reputation: 5473

convert pandas dataframe to list of tuples and drop all pandas datatypes

I need to convert a dataframe into a format that can be inserted into a sql table.

data_tuples = [tuple(row) for row in df.values]

How do I remove all the non python datatypes from a pandas dataframe (including np ints and nans and NaTs)?

Upvotes: 1

Views: 238

Answers (1)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210932

if you want to do it efficiently, use corresponding pandas method - to_sql():

from sqlalchemy import create_engine

# conn = create_engine('postgresql://user:password@host:port/dbname')
conn = create_engine('postgresql+psycopg2://user:password@host:port/dbname')
df.to_sql('table_name', conn)

where conn is a SQLAlchemy engine connection object

Docs: using SQLAlchemy with PostgreSQL

Upvotes: 2

Related Questions