如何解决使用“ pd.read_sql_query”查询索引会导致“ OperationalError:sqlite3.OperationalError在“ index”附近:语法错误”
我有一个非常大的数据框文件,无法将其全部加载到内存中,并且我需要按索引检索很多行,并且这些行是非连续的,因此对带有跳过行和跳过行的pandas.read_csv并没有使用似乎是检索这些行的有效方法。
我发现对于我的情况,数据库可能是处理数据的最佳方式。
我能够将数据发送到sql数据库,但是尝试按索引进行检索时出现错误。
以下是一个最小的示例
import pandas as pd
import numpy as np
from sqlalchemy import create_engine
engine = create_engine('sqlite:///memory.db')
data = pd.DataFrame(np.random.randint(0,100,size=(15,4)),columns=list('ABCD'))
data.head(2)
A B C D
0 64 57 97 99
1 58 31 32 43
我尝试了一些查询,效果很好
pd.read_sql_query('SELECT * FROM data',engine)
index A B C D
0 0 64 57 97 99
1 1 58 31 32 43
2 2 89 56 76 53
3 3 68 13 20 39
4 4 84 34 25 12
5 5 58 10 46 37
6 6 50 85 96 68
7 7 41 55 88 92
8 8 54 72 49 56
9 9 58 20 15 92
10 10 92 20 11 81
11 11 88 6 81 1
12 12 90 90 39 11
13 13 64 84 37 80
14 14 8 82 90 22
有一件事,我注意到原始索引被设置为单独的列。我阅读了to_sql中的文档,但找不到任何将pandas df索引设置为thq sql索引的内容,它显示为“ indexbool,默认为True 将DataFrame索引写为一列。使用index_label作为表中的列名称。”但是看来这意味着,如果未将其设置为true,则索引将不会传输到数据库。
按列查询似乎很好
pd.read_sql_query('SELECT A,C FROM data',engine)
A C
0 64 97
1 58 32
2 89 76
3 68 20
4 84 25
5 58 46
6 50 96
7 41 88
8 54 49
9 58 15
10 92 11
11 88 81
12 90 39
13 64 37
14 8 90
pd.read_sql_query('SELECT A,C FROM data WHERE B=57',engine)
A C
0 64 97
但是从索引列中选择会导致错误
pd.read_sql_query('SELECT A FROM data WHERE index=2',engine)
---------------------------------------------------------------------------
OperationalError Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/base.py in _execute_context(self,dialect,constructor,statement,parameters,*args)
1277 self.dialect.do_execute(
-> 1278 cursor,context
1279 )
12 frames
OperationalError: near "index": syntax error
The above exception was the direct cause of the following exception:
OperationalError Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/default.py in do_execute(self,cursor,context)
591
592 def do_execute(self,context=None):
--> 593 cursor.execute(statement,parameters)
594
595 def do_execute_no_params(self,context=None):
OperationalError: (sqlite3.OperationalError) near "index": syntax error
[SQL: SELECT A FROM data WHERE index=2;]
(Background on this error at: http://sqlalche.me/e/13/e3q8)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。