简体   繁体   中英

Float Array is not converted to int: Python

I have a float numpy array x, which contains values like, 0, .5, 1, 1.5,etc. I want to convert the float values into integers based on some equation and store them in a new array, newx. I did this,

newx=np.zeros(x.shape[0])
    for i in range (x.shape [0]):
        newx[i]=  ((2*x[i]) +1)
    print(newx, v)

However, when printing xnew, I get values like

(array([   1.,    2.,    3.,    4.,    5.,    6.,    7.,    8.,    9.,
         10.,   11.,   12.,   13.,   14.,   15.,   16.,   17.,   18.])

newx must be used in some process, and it must be integer, when I want to use it in that process, I get an error stating that it must be of integer or Boolean type. Can anyone please tell me what mistake I've done?

Thank You.

Numpy is specifically designed for array manipulation. Try not to iterate over a numpy array like you did. You can read about how numpy datatypes are a little different than inbuilt datatypes. This leads to much higher run times.

Anyways Here is a working code for your problem

newx=x*2+1
newx=numpy.int16(newx)      # as easy as this. ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM