Mark
Mark

Reputation: 19

Python-Replace nan value to null in a tuple

How to replace "nan" value to "null" in a tuple.

Example:

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

Expected: (null without quotes)

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

Upvotes: 1

Views: 4023

Answers (1)

Stephen Rauch
Stephen Rauch

Reputation: 49812

If you test a value with math.isnan() you can find nan values like:

Code:

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))

Results:

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

Upvotes: 2

Related Questions