19

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

1

2 Answers 2

32

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
Sign up to request clarification or add additional context in comments.

Comments

5

First creat a connection to your SQL database:

>>> from sqlalchemy import create_engine
>>> engine = create_engine('sqlite:///:memory:', echo=False)

Make your df:

>>> df = pd.DataFrame(index=['aed', 'jfn', 'vivj', 'vfv'],
                      data={'val':[544.8, 5488, 89.3, 87.5]})

Then create the new table on your SQL DB:

>>> df.to_sql('test', con=engine)
>>> engine.execute('SELECT * FROM test').fetchall()
[('aed', 544.8), ('jfn', 5488.0), ('vivj', 89.3), ('vfv', 87.5)]

Taken from Pandas documentation

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.