How to create a numpy array of all True or all False?

前端 未结 7 2111
醉话见心
醉话见心 2020-12-07 09:24

In Python, how do I create a numpy array of arbitrary shape filled with all True or all False?

7条回答
  •  甜味超标
    2020-12-07 09:52

    Quickly ran a timeit to see, if there are any differences between the np.full and np.ones version.

    Answer: No

    import timeit
    
    n_array, n_test = 1000, 10000
    setup = f"import numpy as np; n = {n_array};"
    
    print(f"np.ones: {timeit.timeit('np.ones((n, n), dtype=bool)', number=n_test, setup=setup)}s")
    print(f"np.full: {timeit.timeit('np.full((n, n), True)', number=n_test, setup=setup)}s")
    

    Result:

    np.ones: 0.38416870904620737s
    np.full: 0.38430388597771525s
    


    IMPORTANT

    Regarding the post about np.empty (and I cannot comment, as my reputation is too low):

    DON'T DO THAT. DON'T USE np.empty to initialize an all-True array

    As the array is empty, the memory is not written and there is no guarantee, what your values will be, e.g.

    >>> print(np.empty((4,4), dtype=bool))
    [[ True  True  True  True]
     [ True  True  True  True]
     [ True  True  True  True]
     [ True  True False False]]
    

提交回复
热议问题