Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is shape empty?

Tags:

python

numpy

This code creates a 10-element array.

  1. Why is size 1? Shouldn't it be 0?
  2. why is shape empty? Shouldn't it be 1 dimension?
    In [14]: s = np.array(10)                                                                            

    In [15]: s                                                                                           
    Out[15]: array(10)

    In [16]: s.size                                                                                      
    Out[16]: 1

    In [17]: s.shape                                                                                     
    Out[17]: ()
like image 268
marlon Avatar asked Sep 13 '25 22:09

marlon


1 Answers

If one calls np.array() on arbitrary object that is not iterable, numpy silently creates an empty array with no dimensions. However, its size is 1.

Docs of numpy size tell us that x.size is equivalent to calling np.prod(x.shape). And docs for np.prod state that calling np.prod on empty sequence gives us 1. Probably it is so due to the fact that 1 is a neutral element for multiplication, meaning the following.

Say you have an array [4, 2, 3]. Its elements product is 24. Now you split it in two arrays: [4] and [2, 3]. You have a nice property: np.prod([4, 2, 3]) == np.prod([4]) * np.prod([2, 3]). But if one of the arrays is empty, you want this property still hold: np.prod([4, 2, 3]) == np.prod([]) * np.prod([4, 2, 3]).

like image 127
sooobus Avatar answered Sep 15 '25 10:09

sooobus