Math_reald
Math_reald

Reputation: 315

Python: Numpy dtype U32 - simple if-else statement

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.

Upvotes: 0

Views: 12787

Answers (1)

nathan.medz
nathan.medz

Reputation: 1603

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.

Upvotes: 4

Related Questions