Join the Stack Overflow Community
Stack Overflow is a community of 6.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

This question already has an answer here:


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

share|improve this question

marked as duplicate by Bakuriu, Maxime Lorant, Toto, Frédéric Hamidi, robert Jan 30 '14 at 12:01

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1  
try a.astye(float). Bear in mind, that a must be a numpy array. – Christian Jan 30 '14 at 9:04
    
it says AttributeError: 'numpy.ndarray' object has no attribute 'astye' – veena Jan 30 '14 at 9:06
1  
It is astype and that is what you're looking for – Vincent Jan 30 '14 at 9:07
    
NumPy uses arrays. Not sure what you mean by a NumPy list ... – ssm Jan 30 '14 at 9:08
1  
it is not duplicate. see question in detail. I have blank string as well. – veena Jan 30 '14 at 9:21
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]]
share|improve this answer

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

share|improve this answer
    
what if it has a blank string. check updated question – sam Jan 30 '14 at 9:41
    
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 – FallenAngel Jan 30 '14 at 9:59
    
It also preserves nan values. – FallenAngel Jan 30 '14 at 10:04

Not the answer you're looking for? Browse other questions tagged or ask your own question.