我知道这是一个涉及多个主题的简单主题,但我找不到解决方案。
我所拥有的是一个txt文件,我读入数组并将其转换为Dataframe。 之后,我将变换单个列,使其成为日期/数字。我确信有一种更有效的方法来构建我正在寻找的东西,但它对我有用。
我最终得到的数据框如下:
PSVLD Market Date PSVLD Ticker PSVLD Tenor Date PSVLD Percent of Spot \
1 2017-02-03 .MSCIEA 1M 50.0
2 2017-02-03 .MSCIEA 1M 60.0
3 2017-02-03 .MSCIEA 1M 70.0
4 2017-02-03 .MSCIEA 1M 75.0
5 2017-02-03 .MSCIEA 1M 80.0
6 2017-02-03 .MSCIEA 1M 85.0
7 2017-02-03 .MSCIEA 1M 90.0
8 2017-02-03 .MSCIEA 1M 92.5
9 2017-02-03 .MSCIEA 1M 95.0
10 2017-02-03 .MSCIEA 1M 97.5
PSVLD Vol
1 34.96749
2 34.36383
3 32.58459
4 30.53958
5 28.30699
6 24.74774
7 20.07822
8 17.38867
9 14.58027
10 11.84767
现在我想将这些数据插入数据库。我创建了一个新表,并尝试将此数据帧执行到我的文件中,但它不起作用。
con = sq3.connect('my_db.db')
query = 'CREATE TABLE ImpliedVola (Date date, Ticker varchar(50), Tenor varchar(10),Strike real, IV real)'
con.execute(query)
con.commit()
con.executemany('INSERT INTO ImpliedVola VALUES (?, ?, ?, ?, ?)', df)
但不幸的是,它说了17个绑定。你知道我做错了什么吗?提前谢谢!
ProgrammingError: Incorrect number of bindings supplied. The current statement uses 5, and there are 17 supplied.
答案 0 :(得分:0)
我会使用原生的Pandas DataFrame.to_sql()方法。
演示:
In [41]: import sqlite3
In [42]: con = sqlite3.connect('d:/temp/df.sqlite')
In [43]: df
Out[43]:
PSVLD Market Date PSVLD Ticker PSVLD Tenor Date PSVLD Percent of Spot PSVLD Vol
0 2017-02-03 .MSCIEA 1M 50.0 34.96749
1 2017-02-03 .MSCIEA 1M 60.0 34.36383
2 2017-02-03 .MSCIEA 1M 70.0 32.58459
3 2017-02-03 .MSCIEA 1M 75.0 30.53958
4 2017-02-03 .MSCIEA 1M 80.0 28.30699
5 2017-02-03 .MSCIEA 1M 85.0 24.74774
6 2017-02-03 .MSCIEA 1M 90.0 20.07822
7 2017-02-03 .MSCIEA 1M 92.5 17.38867
8 2017-02-03 .MSCIEA 1M 95.0 14.58027
9 2017-02-03 .MSCIEA 1M 97.5 11.84767
In [44]: df.rename(columns=lambda x: x.replace(' ', '_')).to_sql('ImpliedVola', con, if_exists='replace')
结果:
D:\temp>sqlite3 df.sqlite
SQLite version 3.10.1 2016-01-13 21:41:56
Enter ".help" for usage hints.
sqlite> .mode column
sqlite> .header on
sqlite> select * from ImpliedVola;
index PSVLD_Market_Date PSVLD_Ticker PSVLD_Tenor_Date PSVLD_Percent_of_Spot PSVLD_Vol
---------- ------------------- ------------ ---------------- --------------------- ----------
0 2017-02-03 00:00:00 .MSCIEA 1M 50.0 34.96749
1 2017-02-03 00:00:00 .MSCIEA 1M 60.0 34.36383
2 2017-02-03 00:00:00 .MSCIEA 1M 70.0 32.58459
3 2017-02-03 00:00:00 .MSCIEA 1M 75.0 30.53958
4 2017-02-03 00:00:00 .MSCIEA 1M 80.0 28.30699
5 2017-02-03 00:00:00 .MSCIEA 1M 85.0 24.74774
6 2017-02-03 00:00:00 .MSCIEA 1M 90.0 20.07822
7 2017-02-03 00:00:00 .MSCIEA 1M 92.5 17.38867
8 2017-02-03 00:00:00 .MSCIEA 1M 95.0 14.58027
9 2017-02-03 00:00:00 .MSCIEA 1M 97.5 11.84767