0

I dont understand the following behavior of a numpy array. Given the following array f:

array([u'1.8', u'1.8', u'2.4', u'2.2', u'2.0', u'2.1', u'2.8', u'3.2',
       u'3.3', u'3.4', u'2.8'], dtype='<U32')

for a in f:
    if a > 2.2:
        print "greater"
    else:
        print "smaller"

The result is always greater.

Math_reald
  • 305
  • 3
  • 4
  • 13

1 Answers1

4

This is because the values in your array are Unicode strings, not integers. In python, a numeric type will always be "greater" than a non numeric type on comparison. See this SO answer for a more in depth explanation.

To get the functionality you intended you need to convert the strings to numbers.

Md. Sabbir Ahmed
  • 850
  • 8
  • 22
nathan.medz
  • 1,595
  • 11
  • 21