gpt4 book ai didi

python - 调整pandas read_sql_query NULL值处理?

转载 作者:太空狗 更新时间:2023-10-30 00:19:26 24 4
gpt4 key购买 nike

当我这样做

from sqlalchemy import create_engine
import pandas as pd

engine = create_engine('sqlite://')
conn = engine.connect()
conn.execute("create table test (a float)")
for _ in range(5):
conn.execute("insert into test values (NULL)")

df = pd.read_sql_query("select * from test", engine)
#df = pd.read_sql_table("test", engine)
df.a

结果是一列 None 值,而不是 float("nan")。如果您逐 block 读取具有 NULL 值的浮点列,这会非常烦人。

read_sql_table 版本工作正常,因为我想它可以使用类型信息。

有没有一种简单的方法可以调整 read_sql_query 以将 NULL 值也解释为 float("nan")

最佳答案

好像an issue根据 wesm 在链接页面中的评论,提出了类似的东西 - coerce_float 参数 - 在版本 0.7.2 中被添加到 pandas:

hi arthur, I added an option coerce_float (in the above commit) that converts Decimal -> float and fills None with NaN. Converting Decimal to float is still really slow. Will be part of 0.7.2 to be released soon

虽然pandas.read_sql_query 0.18.1 docs中的描述似乎令人困惑:

coerce_float : boolean, default True

Attempt to convert values to non-string, non-numeric objects (like decimal.Decimal) to floating point, useful for SQL result sets

关于python - 调整pandas read_sql_query NULL值处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30652457/

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