使用chunksize的Pandas read_sql为MySQL数据

时间:2016-10-06 07:32:39

标签: python mysql pandas error-handling pymysql

我试图将MySQL数据库中的大型数据集(1300万行)读入pandas(0.17.1)。根据其中一条在线建议,我使用了chunksize参数来执行此操作。

db = pymysql.connect(HOST,           # localhost
                     port=PORT,      # port
                     user=USER,      # username
                     password=PASSW, # password
                     db=DATABASE)    # name of the data base

df = pd.DataFrame()
query = "SELECT * FROM `table`;"
for chunks in pd.read_sql(query, con=db, chunksize=100000):
    df = df.append(chunks)

但每次我运行此操作时都会收到TypeError: Argument 'rows' has incorrect type (expected list, got tuple)错误。

当我没有使用chunksize参数并因此不生成生成器对象时,这是有效的。我可以看到mysql返回tuple-of-tuples而不是list-of-tuples

所以,我的问题是为什么查询在正常情况下工作,我该怎么做才能确保我从数据库中获取一个元组列表以便我可以使用它?

完整的回溯看起来像这样

TypeError                                 Traceback (most recent call last)
<ipython-input-20-efe94dcd2c70> in <module>()
      8 df_horses = pd.DataFrame()
      9 query = "SELECT * FROM `horses`;"
---> 10 for chunks in pd.read_sql(query, con=db, chunksize=10000):
     11     df_horses = df_horses.append(chunks)
     12 print df_horses.shape

/home/ubuntu/anaconda2/lib/python2.7/site-packages/pandas/io/sql.pyc in _query_iterator(cursor, chunksize, columns, index_col, coerce_float, parse_dates)
   1563                 yield _wrap_result(data, columns, index_col=index_col,
   1564                                    coerce_float=coerce_float,
-> 1565                                    parse_dates=parse_dates)
   1566 
   1567     def read_query(self, sql, index_col=None, coerce_float=True, params=None,

/home/ubuntu/anaconda2/lib/python2.7/site-packages/pandas/io/sql.pyc in _wrap_result(data, columns, index_col, coerce_float, parse_dates)
    135 
    136     frame = DataFrame.from_records(data, columns=columns,
--> 137                                    coerce_float=coerce_float)
    138 
    139     _parse_date_columns(frame, parse_dates)

/home/ubuntu/anaconda2/lib/python2.7/site-packages/pandas/core/frame.pyc in from_records(cls, data, index, exclude, columns, coerce_float, nrows)
    967         else:
    968             arrays, arr_columns = _to_arrays(data, columns,
--> 969                                              coerce_float=coerce_float)
    970 
    971             arr_columns = _ensure_index(arr_columns)

/home/ubuntu/anaconda2/lib/python2.7/site-packages/pandas/core/frame.pyc in _to_arrays(data, columns, coerce_float, dtype)
   5277     if isinstance(data[0], (list, tuple)):
   5278         return _list_to_arrays(data, columns, coerce_float=coerce_float,
-> 5279                                dtype=dtype)
   5280     elif isinstance(data[0], collections.Mapping):
   5281         return _list_of_dict_to_arrays(data, columns,

/home/ubuntu/anaconda2/lib/python2.7/site-packages/pandas/core/frame.pyc in _list_to_arrays(data, columns, coerce_float, dtype)
   5355 def _list_to_arrays(data, columns, coerce_float=False, dtype=None):
   5356     if len(data) > 0 and isinstance(data[0], tuple):
-> 5357         content = list(lib.to_object_array_tuples(data).T)
   5358     else:
   5359         # list of lists

TypeError: Argument 'rows' has incorrect type (expected list, got tuple)

1 个答案:

答案 0 :(得分:0)

当使用chunksize时,我不知道“ pd.read_sql”后面不返回元组列表的原因。实际上,“ pd.read_sql”对于熊猫版本“ 0.23.4”不会引发任何错误。但是我也尝试使用熊猫版本“ 0.16.2”,但遇到的错误与您的错误相同。因此,在编写脚本之前,请务必检查您的熊猫版本。但是我确实知道一种解决熊猫“ 0.16.2”版本中错误的方法。

pandas版本0.16.2

import pymysql as ps
import pandas as pd
db=ps.connect(user="user_name", passwd="password", host = 'host_name', 
              db='database_name')
cursor=db.cursor()
df=pd.DataFrame(columns=['column_name1','column_name2'])
query=""" select column_name1,column_name2 from table_name limit {0},{1}; """
limit=1000000
offset=0
try:
while True:
    cursor.execute(query.format(offset,limit))
    rows=pd.DataFrame(list(cursor.fetchall()),columns= 
                         ['column_name1','column_name2'])
    df=pd.concat([df,rows],ignore_index=True)
    offset=offset+limit
    if len(rows['column_name1'])==0:
        break
except:
    pass