我正在使用 pandas read_sql_query 将数据从 MySQL 数据库表读取到 pandas 数据帧中。此表中的某些列全部为 NULL 值。对于这些列, Pandas 数据框的每一行都包含 None 。对于所有其他列,数据框包含 NaN,其中有一个 NULL 值。谁能解释为什么所有 NULL 列都返回 None ?我如何确保我拥有所有 NaN,希望不进行手动转换? 我应该补充一点,导致这个问题的两列是浮点型的,第三列是 double 型的,
编辑
这是一个例子。列 pef 和 fer 包含数据库中的所有 NULLS。
from sqlalchemy import create_engine
import pandas as pd
import math
querystr = "SELECT * FROM dbname.mytable"
engine = create_engine('mysql+pymysql://username:password@localhost/' + "dbname")
df = pd.read_sql_query(querystr, engine)
df.head()
sys dias pef fer
0 NaN NaN None None
1 159.0 92.666 None None
2 NaN NaN None None
3 NaN NaN None None
4 102.0 63.333 None None
在 MySQL 数据库中,这些列定义为:
Columns:
sys float
dias float
pef float
fer float
我希望列 pef 和 fer 在每一行中包含 NaN,而不是 None。
请您参考如下方法:
该问题是一个 Unresolved 问题,并在此处进行了解释:此处:https://github.com/pandas-dev/pandas/issues/14314
read_sql_query just gets result sets back, without any column type information. If you use the read_sql_table functions, there it uses the column type information through SQLAlchemy.
read_sql_query 似乎只检查列中返回的前 3 个值以确定列的类型。因此,如果前 3 个值是 NULL,它无法确定列的类型,因此返回 None。
因此,部分解决方法是使用 read_sql_table。我更改了我的代码以使用 read_sql_table 并且它按预期返回 NaN 值,即使对于所有 NULL 列也是如此。但在我的实际应用程序中,我确实需要使用 read_sql_query。 所以我现在在返回结果后立即用 NaN 替换任何 None 值:
df.replace([None], np.nan, inplace=True)
