How to convert pandas DataFrame into SQL in Python?
Last Updated :
05 Dec, 2023
In this article, we aim to convert the data frame into an SQL database and then try to read the content from the SQL database using SQL queries or through a table.
Convert Pandas DataFrame into SQL in Python
Below are some steps by which we can export Python dataframe to SQL file in Python:
Step 1: Installation
To deal with SQL in Python, we need to install the Sqlalchemy library using the below-mentioned command by running it in cmd:
pip install sqlalchemy
Step 2: Creating Pandas DataFrame
There is a need to create a pandas data frame to proceed further.
Python3
# import pandas library
import pandas as pd
# create a dataframe
# object from dictionary
dataset = pd.DataFrame({'Names': ['Abhinav', 'Aryan',
'Manthan'],
'DOB': ['10/01/2009', '24/03/2009',
'28/02/2009']})
# show the dataframe
print(dataset)
Output :
Names DOB
0 Abhinav 10/01/2009
1 Aryan 24/03/2009
2 Manthan 28/02/2009
Step 3: Create connection to the SQlite database
After creating the dataset we need to connect the data frame to the database support which is provided for sqlite3.Connection objects.
Python3
# importing sql library
from sqlalchemy import create_engine
# create a reference
# for sql library
engine = create_engine('sqlite://',
echo=False)
# attach the data frame to the sql
# with a name of the table
# as "Employee_Data"
dataset.to_sql('Employee_Data',
con=engine)
# show the complete data
# from Employee_Data table
print(engine.execute("SELECT * FROM Employee_Data").fetchall())
Output:
[(0, 'Abhinav', '10/01/2009'), (1, 'Aryan', '24/03/2009'),
(2, 'Manthan', '28/02/2009')]
Step 4: Adding Data to the Database
After adding the data to the database, it is visible to us in the form of records. Data can also be appended to the previously created database as shown below:
Python3
# Create a dataframe
# object from dictionary
df1 = pd.DataFrame({'Names': ['Sonia', 'Priya'],
'DOB': ['18/10/2009', '14/06/2009']})
# appending new data frame
# to existing data frame
df1.to_sql('Employee_Data',
con=engine,
if_exists='append')
# run a sql query
print(engine.execute("SELECT * FROM Employee_Data").fetchall())
Output:
[(0, 'Abhinav', '10/01/2009'), (1, 'Aryan', '24/03/2009'),
(2, 'Manthan', '28/02/2009'), (0, 'Sonia', '18/10/2009'),
(1, 'Priya', '14/06/2009')]
Step 5: Reading and Displaying SQL Employee Data with Pandas and Indexing by Names
As understood from the above example that although data is appended the indexing again started from 0 only when a new data frame is appended.A data frame can be transferred to the SQL database, the same way data frame can also be read from the SQL database. the return type of the read_sql is data frame.
Python3
# reading the sql database
# with index "Names"
df2 = pd.read_sql('Employee_Data',
con=engine,
index_col='Names',
parse_dates=['DOB'])
# show the dataframe
print(df2)
# print new line
print()
# show the type of df2
print(type(df2))
Output :
id DOB
Names
Sonia 0 2009-10-18
Priya 1 2009-06-14
Example 1: Fetching Names Column from SQL Employee Data
We can also access a particular column in a database rather than the whole table.
Python3
# acccesing only a particular
# column from the database
df3 = pd.read_sql('Employee_Data',
con = engine,
columns = ["Names"])
# show the data
print(df3)
Output :
Names
0 Sonia
1 Priya
Example 2: Retrieving Names Column from SQL Employee Data as a List
If we want to have the data in the database in the form of a list that to is possible.
Python3
# get a particular column
# from a database in the
# form of list
df4 = pd.read_sql('Employee_Data',
con=engine,
index_col='Names',
columns=["Names"])
# show the data
print(df4)
Output :
Empty DataFrame
Columns: []
Index: [Sonia, Priya]
Step 6: Executing SQL Query and Displaying the Result
It is possible to write SQL queries in python using read_sql_query() command and passing the appropriate SQL query and the connection object .
parse_dates: This parameter helps to converts the dates that were originally passed as dates from our side into the genuine dates format.
Python3
# run a sql query in the database
# and store result in a dataframe
df5 = pd.read_sql_query('Select DOB from Employee_Data',
con = engine,
parse_dates = ['DOB'])
# show the dataframe
print(df5)
Output :
DOB
0 2009-10-18
1 2009-06-14
Similar Reads
How to convert pandas DataFrame into JSON in Python?
JSON (JavaScript Object Notation) is a lightweight, easily readable format widely used for data interchange between applications, making it ideal for sharing data across different systems. With Pandas, converting a DataFrame into JSON is simple and efficient using the to_json() function. This articl
7 min read
How to Convert String to Integer in Pandas DataFrame?
Let's see methods to convert string to an integer in Pandas DataFrame: Method 1: Use of Series.astype() method. Syntax: Series.astype(dtype, copy=True, errors=âraiseâ) Parameters: This method will take following parameters: dtype: Data type to convert the series into. (for example str, float, int).c
3 min read
How to Convert Dataframe column into an index in Python-Pandas?
Pandas provide a convenient way to handle data and its transformation. Let's see how can we convert a data frame column to row name or index in Pandas. Create a dataframe first with dict of lists.  Python3 # importing pandas as pd import pandas as pd # Creating a dict of lists data = {'Name':["Akas
2 min read
Python - Convert dict of list to Pandas dataframe
In this article, we will discuss how to convert a dictionary of lists to a pandas dataframe. Method 1: Using DataFrame.from_dict() We will use the from_dict method. This method will construct DataFrame from dict of array-like or dicts. Syntax: pandas.DataFrame.from_dict(dictionary) where dictionary
2 min read
How to Convert Integers to Strings in Pandas DataFrame?
In this article, we'll look at different methods to convert an integer into a string in a Pandas dataframe. In Pandas, there are different functions that we can use to achieve this task : map(str)astype(str)apply(str)applymap(str) Example 1 : In this example, we'll convert each value of a column of
3 min read
How to Convert Pandas DataFrame into a List?
In this article, we will explore the process of converting a Pandas DataFrame into a List, We'll delve into the methods and techniques involved in this conversion, shedding light on the versatility and capabilities of Pandas for handling data structures in Python.Ways to convert Pandas DataFrame Int
7 min read
How To Convert Sklearn Dataset To Pandas Dataframe In Python
In this article, we look at how to convert sklearn dataset to a pandas dataframe in Python. Sklearn and pandas are python libraries that are used widely for data science and machine learning operations. Pandas is majorly focused on data processing, manipulation, cleaning, and visualization whereas s
3 min read
How to Convert Index to Column in Pandas Dataframe?
Pandas is a powerful tool which is used for data analysis and is built on top of the python library. The Pandas library enables users to create and manipulate dataframes (Tables of data) and time series effectively and efficiently. These dataframes can be used for training and testing machine learni
2 min read
How to Convert Integers to Floats in Pandas DataFrame?
Pandas Dataframe provides the freedom to change the data type of column values. We can change them from Integers to Float type, Integer to String, String to Integer, etc. There are 2 methods to convert Integers to Floats: Method 1: Using DataFrame.astype() method Syntax :Â DataFrame.astype(dtype, co
4 min read
How to Convert Integer to Datetime in Pandas DataFrame?
Let's discuss how to convert an Integer to Datetime in it. Now to convert Integers to Datetime in Pandas DataFrame. Syntax of  pd.to_datetimedf['DataFrame Column'] = pd.to_datetime(df['DataFrame Column'], format=specify your format)Create the DataFrame to Convert Integer to Datetime in Pandas Check
2 min read