Detect if a NumPy array contains at least one non-numeric value?

后端 未结 5 1416
逝去的感伤
逝去的感伤 2021-01-30 07:46

I need to write a function which will detect if the input contains at least one value which is non-numeric. If a non-numeric value is found I will raise an error (because the ca

5条回答
  •  离开以前
    2021-01-30 08:34

    This should be faster than iterating and will work regardless of shape.

    numpy.isnan(myarray).any()
    

    Edit: 30x faster:

    import timeit
    s = 'import numpy;a = numpy.arange(10000.).reshape((100,100));a[10,10]=numpy.nan'
    ms = [
        'numpy.isnan(a).any()',
        'any(numpy.isnan(x) for x in a.flatten())']
    for m in ms:
        print "  %.2f s" % timeit.Timer(m, s).timeit(1000), m
    

    Results:

      0.11 s numpy.isnan(a).any()
      3.75 s any(numpy.isnan(x) for x in a.flatten())
    

    Bonus: it works fine for non-array NumPy types:

    >>> a = numpy.float64(42.)
    >>> numpy.isnan(a).any()
    False
    >>> a = numpy.float64(numpy.nan)
    >>> numpy.isnan(a).any()
    True
    

提交回复
热议问题