【发布时间】:2018-10-27 16:58:10
【问题描述】:
我正在尝试从 csv 文件创建一个 sqlite db。经过一番搜索,似乎可以使用 pandas df。我试过遵循一些教程和文档,但我无法弄清楚这个错误。这是我的代码:
# Import libraries
import pandas, csv, sqlite3
# Create sqlite database and cursor
conn = sqlite3.connect('test.db')
c = conn.cursor()
# Create the table of pitches
c.execute("""CREATE TABLE IF NOT EXISTS pitches (
pitch_type text,
game_date text,
release_speed real
)""")
conn.commit()
df = pandas.read_csv('test2.csv')
df.to_sql('pitches', conn, if_exists='append', index=False)
conn.close()
当我运行此代码时,我收到以下错误:
sqlite3.OperationalError: table pitches has no column named SL
SL 是我的 csv 文件第一行中的第一个值。我无法弄清楚为什么它将 csv 值视为列名,除非它认为 csv 的第一行应该是标题并试图将其与表中的列名匹配?我不认为是这样,因为我尝试将第一个值更改为实际的列名并得到相同的错误。
编辑:
当我在 csv 中有标题时,数据框如下所示:
pitch_type game_date release_speed
0 SL 8/31/2017 81.9
1 SL 8/31/2017 84.1
2 SL 8/31/2017 81.9
... ... ... ...
2919 SL 8/1/2017 82.3
2920 CU 8/1/2017 78.7
[2921 rows x 3 columns]
我收到以下错误:
sqlite3.OperationalError: table pitches has no column named game_date
当我从 csv 文件中取出标题时:
SL 8/31/2017 81.9
0 SL 8/31/2017 84.1
1 SL 8/31/2017 81.9
2 SL 8/31/2017 84.1
... .. ... ...
2918 SL 8/1/2017 82.3
2919 CU 8/1/2017 78.7
[2920 rows x 3 columns]
我收到以下错误:
sqlite3.OperationalError: table pitches has no column named SL
编辑#2:
根据this answer,我尝试使用以下代码完全从代码中创建表:
# Import libraries
import pandas, csv, sqlite3
# Create sqlite database and cursor
conn = sqlite3.connect('test.db')
c = conn.cursor()
df = pandas.read_csv('test2.csv')
df.to_sql('pitches', conn, if_exists='append', index=False)
conn.close()
仍然得到
sqlite3.OperationalError: table pitches has no column named SL
错误
编辑#3:
我将建表代码改成如下:
# Create the table of pitches
dropTable = 'DROP TABLE pitches'
c.execute(dropTable)
createTable = "CREATE TABLE IF NOT EXISTS pitches(pitch_type text, game_date text, release_speed real)"
c.execute(createTable)
它现在可以工作了。不知道到底发生了什么变化,因为它在我看来基本相同,但它确实有效。
【问题讨论】:
-
你能发布你的数据框的样子吗?在 csv 文件中分配列名后,您肯定会遇到不同的错误。
-
使用请求的信息进行编辑。