Why does numpy convert int to string and not string to int in a mixed array?

Viewed 173

I have this code:

import numpy as np

def printMe(myData):
    print(myData)
    print(type(myData))
    print("length = " + str(len(myData)))
    for x in myData:
        print(x)
        print(type(x))

if __name__ == '__main__':
    myOtherData = np.array([123,"456"])
    printMe(myOtherData)

The output is

['123' '456']
<class 'numpy.ndarray'>
length = 2
123
<class 'numpy.str_'>
456
<class 'numpy.str_'>

Why does 123 get converted to a string rather than converting the '456' to an integer?

1 Answers

If dtype is not specified in the call np.array then the type will be determined as the minimum type required to hold the objects in the sequence. In your example that will be a string.

Otherwise if you use np.array([123,'456'], dtype=int), then it will try and force int type for all sequence members, this however will fail with value error if one of the members is not suitable to be converted to the desired dtype.

Related