调整pandas read_sql_query NULL值处理?

Ger*_*nuk 6 python pandas

当我做

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
Run Code Online (Sandbox Code Playgroud)

结果是一列None值而不是float("nan").这是非常烦人的,特别是如果您读取具有块值的NULL值的浮点列.

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

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

vmg*_*vmg 1

似乎有人提出了一个问题coerce_float,并且类似的东西 -参数 - 在 0.7.2 版本中被添加到 pandas 中,根据链接页面中 wesm 的评论:

你好,arthur,我添加了一个选项 coerce_float (在上面的提交中),它转换 Decimal -> float 并用 NaN 填充 None 。将 Decimal 转换为 float 仍然非常慢。将成为即将发布的 0.7.2 的一部分

尽管pandas.read_sql_query 0.18.1 文档中的描述似乎令人困惑:

coerce_float :布尔值,默认 True

尝试将非字符串、非数字对象(例如decimal.Decimal)的值转换为浮点型,这对于 SQL 结果集很有用