title: Python comparison ignoring nan
body: <p>While <code>nan == nan</code> is always <code>False</code>, in many cases people want to treat them as equal, and this is enshrined in <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.equals.html" rel="noreferrer"><code>pandas.DataFrame.equals</code></a>:</p>
  
  <blockquote>
    <p>NaNs in the same location are considered equal.</p>
  </blockquote>
  
  <p>Of course, I can write</p>
  
  <pre><code>def equalp(x, y):
      return (x == y) or (math.isnan(x) and math.isnan(y))
  </code></pre>
  
  <p>However, this will fail on containers like <code>[float("nan")]</code> and <code>isnan</code> barfs on non-numbers (so <a href="https://stackoverflow.com/q/4187185/850781">the complexity increases</a>).</p>
  
  <p>So, what do people do to compare complex Python objects which may contain <code>nan</code>?</p>
  
  <p><strong>PS</strong>. Motivation: when comparing two rows in a pandas <code>DataFrame</code>, I would <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_dict.html" rel="noreferrer">convert them into <code>dict</code>s</a> and compare dicts element-wise. </p>
  
  <p><strong>PPS</strong>. When I say "<em>compare</em>", I am thinking <a href="https://www.unix.com/man-page/all/1/diff/" rel="noreferrer"><code>diff</code></a>, not <a href="http://clhs.lisp.se/Body/f_equalp.htm" rel="noreferrer"><code>equalp</code></a>.</p>