如何在 SQLite DB 中存储 Pandas DataFrame

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50803109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:41:08  来源:igfitidea点击:

How to store pandas DataFrame in SQLite DB

pythonpandassqlite

提问by Sriram Chowdary

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

我找不到关于这个主题的好教程。我有一个Pandas数据框,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

我想创建一个数据库和一个表并将数据框存储在其中

回答by MaxU

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

回答by Manuel Martinez

First creat a connection to your SQL database:

首先创建与 SQL 数据库的连接:

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

Make your df:

让你的 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:

然后在您的 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

取自 Pandas 文档