Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting numpy array values into integers

Tags:

python

numpy

My values are currently showing as 1.00+e09 in an array (type float64). I would like them to show 1000000000 instead. Is this possible?

like image 856
Student1001 Avatar asked Sep 02 '26 09:09

Student1001


1 Answers

Make a sample array

In [206]: x=np.array([1e9, 2e10, 1e6])
In [207]: x
Out[207]: array([  1.00000000e+09,   2.00000000e+10,   1.00000000e+06])

We can convert to ints - except notice that the largest one is too large the default int32

In [208]: x.astype(int)
Out[208]: array([ 1000000000, -2147483648,     1000000])

In [212]: x.astype(np.int64)
Out[212]: array([ 1000000000, 20000000000,     1000000], dtype=int64)

Writing a csv with the default format (float) (this is the default format regardless of the array dtype):

In [213]: np.savetxt('text.txt',x)
In [214]: cat text.txt
1.000000000000000000e+09
2.000000000000000000e+10
1.000000000000000000e+06

We can specify a format:

In [215]: np.savetxt('text.txt',x, fmt='%d')
In [216]: cat text.txt
1000000000
20000000000
1000000

Potentially there are 3 issues:

  • integer v float in the array itself, it's dtype
  • display or print of the array
  • writing the array to a csv file
like image 198
hpaulj Avatar answered Sep 04 '26 22:09

hpaulj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!