我试图写一个熊猫数据帧(或可以使用numpy数组)到mysql数据库使用MysqlDB。MysqlDB似乎不理解'nan',我的数据库抛出一个错误,说nan不在字段列表中。我需要找到一种方法将“nan”转换为NoneType。
什么好主意吗?
我试图写一个熊猫数据帧(或可以使用numpy数组)到mysql数据库使用MysqlDB。MysqlDB似乎不理解'nan',我的数据库抛出一个错误,说nan不在字段列表中。我需要找到一种方法将“nan”转换为NoneType。
什么好主意吗?
当前回答
df = df.replace({np.nan: None})
注意:对于<1.4的pandas版本,这会将所有受影响列的dtype更改为object。 为了避免这种情况,请使用以下语法:
df = df.replace(np.nan, None)
这要归功于Github上的这个家伙和Killian Huyghe的评论。
其他回答
经过一番摸索,这招对我很管用:
df = df.astype(object).where(pd.notnull(df),None)
还有另一个选择,它确实对我有用:
df = df.astype(object).replace(np.nan, None)
取代np。nan和None在不同版本的熊猫中完成的不同:
if version.parse(pd.__version__) >= version.parse('1.3.0'):
df = df.replace({np.nan: None})
else:
df = df.where(pd.notnull(df), None)
这解决了熊猫版本<1.3.0的问题,如果df中的值已经为None,则df.replace({np. replace)nan: None})将切换回np。Nan(反之亦然)。
你可以在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'>
在熊猫更新到1.3.2后,我发现推荐的答案和替代建议都不适合我的应用程序,我用蛮力方法解决了安全问题:
buf = df.to_json(orient='records')
recs = json.loads(buf)