我有一个非常大的数据帧文件,无法全部加载到内存中,我需要按索引检索许多行,而这些行是不连续的,因此使用pandas.read_csv和skiprows似乎不是检索这些行的有效方法。
我看到,就我的情况而言,数据库可能是处理我的数据的最佳方式。
我能够将数据发送到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,则索引将不会传输到db。
按列查询似乎工作正常
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, statement, parameters, 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, statement, parameters, context)
591
592 def do_execute(self, cursor, statement, parameters, context=None):
--> 593 cursor.execute(statement, parameters)
594
595 def do_execute_no_params(self, cursor, statement, 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)