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
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter