Pandas DataFrame 到 SQLite

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14586608/
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-13 20:37:30  来源:igfitidea点击:

Pandas DataFrame to SqLite

pythonsqlitepandas

提问by msalese

I'm learning how to write a pandas dataFrame to SQLite db.

我正在学习如何将 Pandas 数据帧写入 SQLite db。

I went in one example code:

我进入了一个示例代码:

import pandas as pd
import pandas.io.sql as pd_sql
import sqlite3 as sql

con = sql.connect("/home/msalese/Documents/ipyNotebooks/tmp.db")
df =pd.DataFrame({'TestData':[1,2,3,4,5,6,7,8,9]})
pd_sql.write_frame(df, "tbldata2", con)

But above code rise an exception:

但是上面的代码出现了一个异常:

---------------------------------------------------------------------------
InterfaceError                            Traceback (most recent call last)
<ipython-input-31-c844f7e3f2e6> in <module>()
----> 1 pd_sql.write_frame(df, "tbldata2", con)

/opt/epdFree7.3.2/lib/python2.7/site-packages/pandas-0.10.1-py2.7-linux-x86_64.egg/pandas/io/sql.pyc in write_frame(frame, name, con, flavor, if_exists, **kwargs)
208     if func is None:
209         raise NotImplementedError
--> 210     func(frame, name, safe_names, cur)
211     cur.close()
212     con.commit()

/opt/epdFree7.3.2/lib/python2.7/site-packages/pandas-0.10.1-py2.7-linux-x86_64.egg/pandas/io/sql.pyc in _write_sqlite(frame, table, names, cur)
219         table, col_names, wildcards)
220     data = [tuple(x) for x in frame.values]
--> 221     cur.executemany(insert_query, data)
222 
223 def _write_mysql(frame, table, names, cur):

InterfaceError: Error binding parameter 0 - probably unsupported type.

I think that the problem is on code line 220. If I try :

我认为问题出在代码行 220 上。如果我尝试:

[tuple(x) for x in df.values]

the result is:

结果是:

[(1,), (2,), (3,), (4,), (5,), (6,), (7,), (8,), (9,)]

may be commas give noise to sqlite db.

可能是逗号给 sqlite db 带来噪音。

I'm not sure, can someone give me an hint, please ?

我不确定,有人可以给我提示吗?

回答by D. A.

Refer to the answer from @unutbu in the comments.

请参阅评论中@unutbu 的回答。

The problem is avoided if you specify a float dtype. For example,

如果指定 float dtype,则可以避免该问题。例如,

df = pd.DataFrame({'TestData': [1, 2, 3, 4, 5, 6, 7, 8, 9]}, dtype='float')