pandas的read_sql函数没有读取所有的行。
pandas的read_sql函数没有读取所有的行。
我同时通过pandas的read_sql和外部应用程序(DbVisualizer)来运行完全相同的查询。
DbVisualizer返回206行,而pandas返回178行。
我尝试根据How to create a large pandas dataframe from an sql query without running out of memory?提供的信息,按块从pandas中读取数据,但没有改变。
可能的原因是什么?有什么解决办法?
查询语句:
select * from rainy_days where year=’2010’ and day=‘weekend’
列包括:日期、年份、工作日、当天的降雨量、温度、地理位置(每个位置一行)、风力测量、前一天的降雨量等。
完整的Python代码(不包括连接详细信息)是:
import pandas from sqlalchemy import create_engine engine = create_engine( 'postgresql://user:pass@server.com/weatherhist?port=5439', ) query = """ select * from rainy_days where year=’2010’ and day=‘weekend’ """ df = pandas.read_sql(query, con=engine)
pandas的read_sql函数在读取数据库数据时可能会出现没有读取到所有行的问题。问题的原因是pandas返回的DataFrame默认是“packed”(压缩)的,而且显示的结果因情况而异。解决方法是在尝试打印DataFrame之前/时使用“unpacking”(解包)操作符(*)。具体操作如下:
print(*df)
这也被称为Ruby爱好者的“splat”操作符。
为了了解更多相关信息,请参考以下参考资料和教程:
- https://treyhunner.com/2018/10/asterisks-in-python-what-they-are-and-how-to-use-them/
- https://www.geeksforgeeks.org/python-star-or-asterisk-operator/
- https://medium.com/understand-the-python/understanding-the-asterisk-of-python-8b9daaa4a558
- https://towardsdatascience.com/unpacking-operators-in-python-306ae44cd480
读取所有行的问题可能是由于使用了`pandas`的`read_sql`函数,而该函数在读取数据时没有读取所有的行。这个问题的原因可能是因为使用了`pure engine.execute`方法,并且需要手动处理格式。
解决这个问题的方法是使用`clickhouse-sqlalchemy`库的`execute`方法,并且手动处理格式。
以下是解决这个问题的代码示例:
from sqlalchemy import create_engine from clickhouse_sqlalchemy import make_session, get_declarative_base # 创建 ClickHouse 连接 engine = create_engine('clickhouse+native://user:password@clickhouse-host:port/database') # 创建会话和基本模型 session = make_session(engine) Base = get_declarative_base(engine) # 定义 ClickHouse 表模型 class MyTable(Base): __tablename__ = 'my_table' id = Column(Int32, primary_key=True) name = Column(String) # 使用 execute 方法查询数据 query = 'SELECT * FROM my_table' result = session.execute(query) # 将结果转换为 Pandas DataFrame df = pd.DataFrame(result.fetchall(), columns=result.keys()) # 打印 DataFrame print(df)
这样,就可以使用`execute`方法来读取所有的行,并且手动处理格式,解决了`pandas read_sql`不读取所有行的问题。