Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am trying to convert a list that contains numeric values and None values to numpy.array, such that None is replaces with numpy.nan.

For example:

my_list = [3,5,6,None,6,None]

# My desired result: 
my_array = numpy.array([3,5,6,np.nan,6,np.nan]) 

Naive approach fails:

>>> my_list
[3, 5, 6, None, 6, None]
>>> np.array(my_list)
array([3, 5, 6, None, 6, None], dtype=object) # very limited 
>>> _ * 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'

>>> my_array # normal array can handle these operations
array([  3.,   5.,   6.,  nan,   6.,  nan])
>>> my_array * 2
array([  6.,  10.,  12.,  nan,  12.,  nan])

What is the best way to solve this problem?

share|improve this question
add comment

2 Answers

up vote 4 down vote accepted

You simply have to explicitly declare the data type:

>>> my_list = [3, 5, 6, None, 6, None]
>>> np.array(my_list, dtype=np.float)
array([  3.,   5.,   6.,  nan,   6.,  nan])
share|improve this answer
    
I had a feeling that I was missing something simple...Thank You –  Akavall Oct 18 '13 at 18:12
add comment

What about

my_array = np.array(map(lambda x: numpy.nan if x==None else x, my_list))
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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