简体   繁体   English

在python中用空字符串替换nan

[英]Replace nan with empty string in python

My requirement: I want to replace nan with "" (empty string)我的要求:我想用"" (空字符串)替换nan

Example例子

data = """{"name":"siva","id":"111","grade":"12","job_id":nan,"location":"ananb"}"""

If you see above example, i just want to replace nan (Not a Number) not the string consists of nan(ananb)如果你看到上面的例子,我只想替换nan (不是数字)而不是由 nan(ananb) 组成的字符串

Can any one suggest a solution for this?任何人都可以为此提出解决方案吗?

A non generic solution for your specific example could be您的特定示例的非通用解决方案可能是

data.replace(":nan",":")

This wouldn't replace actual values of the dictionary这不会替换字典的实际值

You can use the string.replace method.您可以使用 string.replace 方法。

data.replace("nan","")

Hope this solves your problem.希望这能解决您的问题。

更好的方法是使用正则表达式 ike 替换任何没有被其他字母包围的nan匹配项:

import re

print(re.sub("\\Wnan\\W", "", data))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM