简体   繁体   中英

Operations with Numpy arrays with zero dimensions

Is a numpy array of shape (0,10) a numpy array of shape (10). I'm writing a very simple function that will alternate between 2 and 3 dimensions and I am wondering know whether the output of something like this:

def Pick(N = 0, F, R, Choice=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]):
    if N==0:
        return np.array(np.random.choice(Choice,size=(F,R)))
    else:
        return np.array(np.random.choice(Choice,size=(N,F,R)))

will behave the same as the output of:

 def Pick(N = 0, F, R, Choice=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]):
    return np.array(np.random.choice(Choice,size=(N,F,R)))
     

Theoretically these should be the same but when I try.

a =np.full((10,10,10),1)

then

a+a 

I get a (10,10,10) np.array of 2's. But if I try

b=np.full((0,10,10,10),1)

then

b+b 

This is the only result I receive

 array([], shape=(0, 10, 10, 10), dtype=int64)

any ideas as to why this is?

Abstractly, an array of shape (N,M,L) can be represented identically by an array of shape (<>,N,<>,M,<>,L,<>), where <> can be substituted for a sequence of 1s with arbitrary finite length. Consider the set of indexes corresponding to each data point — if one dimension is of length 0, what index corresponding to that dimension can data points bear? This should explain why defining a numpy array as you have yields the [] result — because you have defined an empty array. Defining

a = np.full((10,10,10),1)
b = np.full((10,10,10,1),1)

the

a+b 

operation broadcasts appropriately (and) yields the expected result.

A 0 dimension has the same meaning as a 1, 2 or other positive integer:

In [437]: np.ones((2,3),int)                                                                         
Out[437]: 
array([[1, 1, 1],        # 2*3 elements
       [1, 1, 1]])
In [438]: np.ones((1,3),int)                                                                         
Out[438]: array([[1, 1, 1]])          # 1*3 elements
In [439]: np.ones((0,3),int)                                                                         
Out[439]: array([], shape=(0, 3), dtype=int64)     # 0*3 elements

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM