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

什么好主意吗?


当前回答

在替换为where语句之前,将numpy NaN转换为pandas NA:

df = df.replace(np.NaN, pd.NA).where(df.notnull(), None)

其他回答

这招对我很管用:

df = df.fillna(0)

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

df = df.astype(object).replace(np.nan, 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])

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

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