13

I have a numpy.ndarray

a = [['-0.99' '' '0.56' ..., '0.56' '-2.02' '-0.96']]

how to convert it to int?

output :

a = [[-0.99 0.0 0.56 ..., 0.56 -2.02 -0.96]]

I want 0.0 in place of blank ''

veena
  • 815
  • 2
  • 7
  • 11

2 Answers2

15
import numpy as np

a = np.array([['-0.99', '', '0.56', '0.56', '-2.02', '-0.96']])
a[a == ''] = 0.0
a = a.astype(np.float)

Result is:

[[-0.99  0.    0.56  0.56 -2.02 -0.96]]

Your values are floats, not integers. It is not clear if you want a list of lists or a numpy array as your end result. You can easily get a list of lists like this:

a = a.tolist()

Result:

[[-0.99, 0.0, 0.56, 0.56, -2.02, -0.96]]
abudis
  • 2,841
  • 6
  • 32
  • 41
1

That is a pure python solution and it produces a list .

With simple python operations, you can map inner list with float. That will convert all string elements to float and assign it as the zero indexed item of your list.

a = [['-0.99' , '0.56' , '0.56' , '0.56', '-2.02' , '-0.96']]

a[0] = map(float, a[0])

print a
[[-0.99, 0.56, 0.56, 0.56, -2.02, -0.96]]

Update: Try the following

a = [['-0.99' , '0.56' , '0.56' , '0.56', '-2.02' , '-0.96', '', 'nan']]
for _position, _value in enumerate(a[0]):
    try:
        _new_value = float(_value)
    except ValueError:
        _new_value = 0.0
    a[0][_position] = _new_value

[[-0.99, 0.56, 0.56, 0.56, -2.02, -0.96, 0.0, nan]]

It enumerates the objects in the list and try to parse them to float, if it fails, then replace it with 0.0

Mp0int
  • 18,172
  • 15
  • 83
  • 114