Importing data from a PostgreSQL database to a Pandas DataFrame | by Alexandre Stamm | Medium
Wed Mar 20 2024 12:19:49 GMT+0000 (Coordinated Universal Time)
Saved by
@talaviyabhavik
def sql_to_dataframe(conn, query, column_names):
“””
Import data from a PostgreSQL database using a SELECT query
“””
cursor = conn.cursor()
try:
cursor.execute(query)
except (Exception, psycopg2.DatabaseError) as error:
print(“Error: %s” % error)
cursor.close()
return 1
# The execute returns a list of tuples:
tuples_list = cursor.fetchall()
cursor.close()
# Now we need to transform the list into a pandas DataFrame:
df = pd.DataFrame(tuples_list, columns=column_names)
return df
content_copyCOPY
https://medium.com/@alestamm/importing-data-from-a-postgresql-database-to-a-pandas-dataframe-5f4bffcd8bb2
Comments