Pandas read_sql_query 为某些列中的所有值返回 None

Pandas read_sql_query returning None for all values in some columns

我正在使用 pandas read_sql_query 将数据从 MySQL 数据库 table 读取到 pandas 数据帧中。此 table 中的某些列全部为 NULL 值。对于这些列,pandas 数据框的每一行都包含 None。对于所有其他列,数据框包含 NaN,其中有一个 NULL 值。谁能解释为什么 None 返回所有 NULL 列?我如何确保我拥有所有 NaN,希望不进行手动转换? 我应该补充一点,导致这个问题的两列是 float,第三列是 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。

该问题是一个未解决的问题,在此处进行了解释:此处: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,则它无法确定列的类型,因此 returns None.

因此,部分解决方法是使用 read_sql_table。我更改了我的代码以使用 read_sql_table 并且它的 returns NaN 值符合预期,即使对于所有 NULL 列也是如此。但是在我的实际应用程序中,我确实需要使用 read_sql_query. 所以我现在在返回结果后立即用 NaN 替换任何 None 值:

df.replace([None], np.nan, inplace=True)

我尝试使用 read_sql_table,但它没有解决我的问题。此外,我发现接受的答案实际上会产生其他问题。

对于我的数据,只有 'None' 而不是 NaN 的列是 pandas 认为是对象的列。对于日期时间,缺失的是 NaT;对于浮点数,缺失值是 NaN。

read_sql_table 对我不起作用,并返回与 read_sql 相同的问题。然后我尝试了接受的答案和 运行 df.replace([None], np.nan, inplace=True)。这实际上将我所有缺少数据的日期时间对象更改为对象数据类型。所以现在我必须将它们改回日期时间,这可能会根据您的数据大小征税。

相反,我建议您首先识别 df 中的对象 dtype 字段,然后替换 None:

obj_columns = list(df.select_dtypes(include=['object']).columns.values)
df[obj_columns] = df[obj_columns].replace([None], np.nan)