First install Python library Psycopg2 to connect to PostgreSQL:
!pip install psycopg2
Now import the necessary libraries:
import pandas as pd
import psycopg2 as pg
import pandas.io.sql as psql
Connect to the DB Server:
conn = pg.connect("postgres://username:password@server:port/dbname")
Execute a Query:
df = pd.read_sql('select* from table_name', conn)
df.head()
great
ReplyDeleteConnecting PostgreSQL with Python through Psycopg2 and Pandas is a practical way to bring database data into a DataFrame for analysis. The example demonstrates installing the required library, importing pandas and psycopg2, and establishing a database connection before executing a SQL query. Pandas Online Course
ReplyDeleteOnce the connection is established, pd.read_sql() can be used to retrieve records directly into a Pandas DataFrame. Calling df.head() then provides a quick way to inspect the first few rows and verify that the query has returned data as expected. Python Course in Chennai Python Projects For Final Year
ReplyDelete