我试图写一个熊猫数据帧(或可以使用numpy数组)到mysql数据库使用MysqlDB。MysqlDB似乎不理解'nan',我的数据库抛出一个错误,说nan不在字段列表中。我需要找到一种方法将“nan”转换为NoneType。

什么好主意吗?


当前回答

经过一番摸索,这招对我很管用:

df = df.astype(object).where(pd.notnull(df),None)

其他回答

你可以在numpy数组中用None替换nan:

>>> x = np.array([1, np.nan, 3])
>>> y = np.where(np.isnan(x), None, x)
>>> print y
[1.0 None 3.0]
>>> print type(y[1])
<type 'NoneType'>

有时使用此代码更好。注意np指的是numpy:

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

我相信最干净的方法是使用pandas. datafframe .to_numpy()方法中的na_value参数(docs):

na_value:任意,可选 用于缺失值的值。默认值取决于dtype和DataFrame列的dtypes。 1.1.0新版功能。

例如,你可以使用None替换NaN的字典

columns = df.columns.tolist()
dicts_with_nan_replaced = [
    dict(zip(columns, x))
    for x in df.to_numpy(na_value=None)
]

还有另一个选择,它确实对我有用:

df = df.astype(object).replace(np.nan, None)

在熊猫更新到1.3.2后,我发现推荐的答案和替代建议都不适合我的应用程序,我用蛮力方法解决了安全问题:

buf = df.to_json(orient='records')
recs = json.loads(buf)