Student1001
Student1001

Reputation: 111

Converting numpy array values into integers

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?

Upvotes: 6

Views: 20675

Answers (2)

gregory
gregory

Reputation: 13023

It is a printing option, see the documentation: printing options. Briefly stated: you need to use the suppress option when printing:

np.set_printoptions(suppress=True)  # for small floating point.

np.set_printoptions(suppress=True, formatter={'all':lambda x: str(x)})

Upvotes: 0

hpaulj
hpaulj

Reputation: 231698

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

Upvotes: 12

Related Questions