Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store pandas DataFrame in SQLite DB

I am unable to find good tutorial on this topic. I am having a pandas data frame, df as

Fu(varchar)  val

aed          544.8
jfn          5488
vivj         89.3
vffv         87.5

I want to create a database and a table and store the dataframe in it

like image 566
Sriram Chowdary Avatar asked Jun 11 '18 17:06

Sriram Chowdary


People also ask

How does Python store data in SQLite?

Inserting data using pythonImport sqlite3 package. Create a connection object using the connect() method by passing the name of the database as a parameter to it. The cursor() method returns a cursor object using which you can communicate with SQLite3.

Does pandas use SQLite?

sqlite3 can be used with Pandas to read SQL data to the familiar Pandas DataFrame.

Why use SQLite to store your pandas data?

Using SQLite to store your Pandas… | by Alan Jones | Towards Data Science The SQLite database is a built-in feature of Python and a very useful one, at that. It is not a complete implementation of SQL but it has all the features that you need for a personal database or even a backend for a data-driven web site.

How to write data from Dataframe to a table in SQLite?

We can use function to_sql of DataFrame to write data into a table in SQLite or any other SQL databases such as Oracle, SQL Server, MySQL, Teradata, etc. The above code snippets creates a table Users in the example.sqlite database and then close the database connection. There are several optional parameters can be used.

How do I read a SQLite database in Python?

SQLite Database with Pandas. An SQLite database can be read directly into Python Pandas (a data analysis library). In this article we’ll demonstrate loading data from an SQLite database table into a Python Pandas Data Frame. We’ll also briefly cover the creation of the sqlite database table using Python.

How to convert pandas Dataframe to SQL?

Here is the full Python code to get from Pandas DataFrame to SQL: Run the code, and you’ll get the following results: Now let’s see how to go from the DataFrame to SQL, and then back to the DataFrame. For this example, you can create a new database called: ‘ test_database_2 ‘


1 Answers

Demo:

>>> import sqlite3
>>> conn = sqlite3.connect('d:/temp/test.sqlite')
>>> df.to_sql('new_table_name', conn, if_exists='replace', index=False)
>>> pd.read_sql('select * from new_table_name', conn)
     Fu     val
0   aed   544.8
1   jfn  5488.0
2  vivj    89.3
3  vffv    87.5
like image 188
MaxU - stop WAR against UA Avatar answered Oct 18 '22 10:10

MaxU - stop WAR against UA