gpt4 book ai didi

python - Pandas read_sql with chunksize 给出了 MySQL 数据的参数错误

转载 作者:行者123 更新时间:2023-11-29 20:14:21 24 4
gpt4 key购买 nike

我正在尝试将大型数据集(1300 万行)从 MySQL 数据库读取到 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 invalid 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)

最佳答案

我不知道使用 chunksize 时“pd.read_sql”不返回元组列表的原因。事实上,“pd.read_sql”不会引发 pandas 版本“0.23.4”的任何错误。但我也尝试使用 pandas 版本“0.16.2”,遇到与您相同的错误。因此,请在编写脚本之前检查您的 pandas 版本。但我确实知道一种方法可以克服 pandas 版本“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

关于python - Pandas read_sql with chunksize 给出了 MySQL 数据的参数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39890113/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com