Home > Net >  How can I convert a numpy array of float type into a numpy array of int type?
How can I convert a numpy array of float type into a numpy array of int type?

Time:09-21

I have the following source code:

npW_x = np.array(my_np_array)
npW_round_111 = np.around(npW_x, decimals=0)
sum_x_111 = np.sum(npW_round_111, axis=1)

np.savetxt("file1.txt", sum_x_111)

File output

3.200000000000000000e 01
5.500000000000000000e 01
3.300000000000000000e 01
4.900000000000000000e 01
5.200000000000000000e 01
5.500000000000000000e 01
3.800000000000000000e 01
5.200000000000000000e 01
5.100000000000000000e 01
3.100000000000000000e 01
3.100000000000000000e 01
3.200000000000000000e 01
5.100000000000000000e 01
... ... ... ... ... ...

The expected output is as follows:

3
6
3
5
5
6
4
5
5
3
3
3
5
... ... ... ... ... ...

How can I do this?

CodePudding user response:

In [385]: npW_x = np.random.rand(4,5)*10
     ...: npW_round_111 = np.around(npW_x, decimals=0)
     ...: sum_x_111 = np.sum(npW_round_111, axis=1)
     ...: 
In [386]: sum_x_111
Out[386]: array([38., 25., 24., 30.])

save with default fmt (Read and reread the np.savetxt docs!)

In [387]: np.savetxt('test',sum_x_111)
In [388]: cat test
3.800000000000000000e 01
2.500000000000000000e 01
2.400000000000000000e 01
3.000000000000000000e 01

save with int format:

In [389]: np.savetxt('test',sum_x_111, fmt='d')
In [390]: cat test
        38
        25
        24
        30

conversion in memory to int:

In [391]: In [391]: sum_x_111.astype(int)
Out[391]: array([38, 25, 24, 30])

CodePudding user response:

You can use astype() function for this

I'm considering npW_x to be the array which needs to be converted into int array.

npW_x = np.array(my_np_array)
npW_x = npW_x.astype('int32')

Now, it should be converted into an integer numpy array.

Edit:

I have added the full code, so that you can try

npW_x = np.array(my_np_array)
npW_x = npW_x.astype('int32')
sum_x_111 = np.sum(npW_x, axis=1)
np.savetxt("file1.txt", sum_x_111)

Hope it resolved your problem.

CodePudding user response:


arr = np.asarray([3.200000000000000000e 01,
5.500000000000000000e 01,
3.300000000000000000e 01,
4.900000000000000000e 01,
5.200000000000000000e 01,
5.500000000000000000e 01,
3.800000000000000000e 01,
5.200000000000000000e 01,
5.100000000000000000e 01,
3.100000000000000000e 01,
3.100000000000000000e 01,
3.200000000000000000e 01,
5.100000000000000000e 01])

arr

array([32. , 55. , 33. , 49. , 52. , 55. , 38. , 52. , 51. , 31. , 31. ,
       32. ,  5.1])
np.around(np.where(arr//10, arr/10, arr)).astype('int')

get

array([3, 6, 3, 5, 5, 6, 4, 5, 5, 3, 3, 3, 5])
  • Related