Best way to initialize and fill an numpy array?

前端 未结 5 1762
闹比i
闹比i 2020-12-29 03:10

I want to initialize and fill a numpy array. What is the best way?

This works as I expect:

>>> import numpy as np
>>>          


        
5条回答
  •  礼貌的吻别
    2020-12-29 03:50

    I find this easy to remember:

    numpy.array([numpy.nan]*3)
    

    Out of curiosity, I timed it, and both @JoshAdel's answer and @shx2's answer are far faster than mine with large arrays.

    In [34]: %timeit -n10000 numpy.array([numpy.nan]*10000)
    10000 loops, best of 3: 273 µs per loop
    
    In [35]: %timeit -n10000 numpy.empty(10000)* numpy.nan
    10000 loops, best of 3: 6.5 µs per loop
    
    In [36]: %timeit -n10000 numpy.full(10000, numpy.nan)
    10000 loops, best of 3: 5.42 µs per loop
    

提交回复
热议问题