14

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 ''

8
  • 1
    try a.astye(float). Bear in mind, that a must be a numpy array. Commented Jan 30, 2014 at 9:04
  • 1
    It is astype and that is what you're looking for Commented Jan 30, 2014 at 9:07
  • 1
    That's a float array, and you want a.astype(np.float). Commented Jan 30, 2014 at 9:11
  • 1
    it is not duplicate. see question in detail. I have blank string as well. Commented Jan 30, 2014 at 9:21
  • 1
    if you are on Python 3, then it should np.array(a, dtype=np.float32) Commented Apr 27, 2020 at 5:46

2 Answers 2

16
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]]
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

Ok I update my answer and make it handle everything in your list. If it can not parse, then it will replace with 0.0
It also preserves nan values.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.