Python-在元组中将nan值替换为null

时间:2018-01-29 04:30:57

标签: python python-3.x

如何在元组中将“nan”值替换为“null”。

示例:

tuples = [tuple(x) for x in data.values]
tuples=[(10001, nan, 'test1'), (10002, 35.0, 'test2')]

预期:(无引号为空)

tuples=[(10001, null, 'test1'), (10002, 35.0, 'test2')]

1 个答案:

答案 0 :(得分:1)

如果使用math.isnan()测试值,则可以找到如下的纳米值:

代码:

import math
import json

tuples = [(10001, float('nan'), 'test1'), (10002, 35.0, 'test2')]
new_tuples = [
    tuple(None if isinstance(i, float) and math.isnan(i) else i for i in t)
    for t in tuples
]

print(tuples)
print(json.dumps(new_tuples))

结果:

[(10001, nan, 'test1'), (10002, 35.0, 'test2')]
[[10001, null, "test1"], [10002, 35.0, "test2"]]