简体   繁体   中英

How do you check for nan in python jmespath?

Assume import jmespath . Let's say I have some data like:

In [3]: data=[{'foo':10}, {'foo':float('nan')}, {'foo':32}]

In [4]: data
Out[4]: [{'foo': 10}, {'foo': nan}, {'foo': 32}]

I want to use jmespath to count the number of nodes that are nan. I can't seem to get it to. I can count the non-nan nodes like so:

jmespath.search('length([?@.foo.abs(@) >= `0`])',data)

I have tried comparing to nan and NaN but that doesn't work, and frankly it shouldn't because nan doesn't equal nan. However, there is no is_nan() function that I can see. I suppose I could convert to string and then compare them? That seems like a last resort. Is there some is_nan I don't see documented?

Context

  • python 2.x or python 3.x
  • jmespath query

Problem

  • how to construct a query that counts the instances of nan (not a number)

Solution

  • use Jmespath not-expression ! (exclaimation point) in conjunction with the abs() function
  • use jmespath length() function to count the results

Example

jmespath.compile('''[*].foo|[? !(abs(@) >= `0`)]|length([*])''').search(data)

Details

  • Jmespath type() function treats nan as number
  • Using not-expression in combination with abs(@) greater-than or equal-to zero returns true for nan

Pitfalls

  • Jmespath errors out with invalid type for value if an incompatible type is passed into abs() (such as string).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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