Part 5.1 !! Pandas DataFrame to PostgreSQL using Python

How to read data from PostgreSQL to Pandas DataFrame?

Learner CARES
Analytics Vidhya
3 min readNov 30, 2020

--

Prerequisites

Python 3.8.3 : Anaconda download link

PostgreSQL 13 : Download link

Psycopg2 : To install Psycopg2 use the command: pip install psycopg2

Objective

Generally we create training and testing data by importing csv file into pandas DataFrame but when we have large data stored in database server then we need a method to extract it into pandas DataFrame directly from database server. For this objective, we will learn step by step working code for different methods for doing it.

Step 1 : Import libraries

Step 2 : Specify the connection parameters

Step 3 : Support Functions

Step 4: Perform main task

Method 1 : Using psycopg2

Method 2 : Using psycopg2 and pd.read_sql_query()

Method 3: Using sqlalchemy

Conclusion : This ends our Part 5.1. In this tutorial we have learned How to read data from PostgreSQL bdatabase to Pandas DataFrame?

All code for this article is available as a Jupyter Notebook on GitHub.

Next Part 5.2 : Extract, Transform, and Load PostgreSQL Data in Python

Previous Learning :

Part 1: Introduction , Connection & Database Creation

Part 2 Create Table in PostgreSQL Database Using Python

Part 3.1: Insert Bulk Data Using executemany() Into PostgreSQL Database

Part 3.2: Insert Bulk Data Using execute_batch() Into PostgreSQL Database

Part 3.3: Insert Bulk Data Using execute_values() method into PostgreSQL Database using Python

Part 3.4: Insert Bulk Data Using mogrify() Into PostgreSQL Database

Part 3.5: Insert Bulk Data Using copy_from() Into PostgreSQL Database

Part 3.6 : Insert Bulk Data Using copy_from() with StringIO Into PostgreSQL Database

Part 3.7 : Insert Bulk Data Using to_sql()(alchemy) Into PostgreSQL Database

Part 4: Comparison of Methods for Importing bulk CSV data Into PostgreSQL Using Python

Stay Positive !! Stay Safe !! Keep Learning :):)

Thanks you for reading! !

--

--

Learner CARES
Analytics Vidhya

Data Scientist, Kaggle Expert (https://www.kaggle.com/itsmohammadshahid/code?scroll=true). Focusing on only one thing — To help people learn📚 🌱🎯️🏆