首页 > 解决方案 > NDArray 的这种行为是否正确?

问题描述

我觉得 ndarray 对象的行为不正确。我使用下面的代码行创建了一个

c = np.ones((5,0), dtype=np.int32)

下面给出了一些命令和输出

print(c)
[]
c
array([], shape=(5, 0), dtype=int32)
c[0]
array([], dtype=int32)
print(c[0])
[]

就像空数组包含空数组一样。我可以赋值,但这个值丢失了,它不显示。

print(c)
[]
c.shape
(5, 0)
c[0]=10
print(c)
[]
print(c[0])
[]

(5,0) 数组是什么意思?a 和 c 有什么区别?

a = np.ones((5,), dtype=np.int32)
c = np.ones((5,0), dtype=np.int32)

对不起,我是 Python 新手,所以我的知识非常基础。

标签: pythonpython-3.xnumpynumpy-ndarray

解决方案


In [43]: c = np.ones((5,0), dtype=np.int32)                                                                  
In [44]: c                                                                                                   
Out[44]: array([], shape=(5, 0), dtype=int32)
In [45]: c.size                                                                                              
Out[45]: 0
In [46]: np.ones(5).size                                                                                     
Out[46]: 5

数组的大小或元素数量是其形状的乘积。为此。 c_ 是一个不包含任何内容的二维数组。 5*0 = 0c

如果我尝试将值分配给 的列,c则会出现错误:

In [49]: c[:,0]=10                                                                                           
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-49-7baeeb61be4e> in <module>
----> 1 c[:,0]=10

IndexError: index 0 is out of bounds for axis 1 with size 0

你的任务:

In [51]: c[0] = 10                                                                                           

实际上是:

In [52]: c[0,:] = np.array(10) 

之所以有效,是因为c[0,:].shapeis (0,),并且形状为 () 或 (1,) 的数组可以“广播”到该目标。这是一个棘手的广播案例。

一个更有指导意义的赋值案例c是我们尝试分配 2 个值:

In [57]: c[[0,1],:] = np.array([1,2])                                                                        
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-57-9ad1339293df> in <module>
----> 1 c[[0,1],:] = np.array([1,2])

ValueError: shape mismatch: value array of shape (2,) could not be broadcast to indexing result of shape (2,0)

源数组是形状为 (2,) 的 1d。目标是具有形状 (2,0) 的 2d。

一般来说,形状为 0 的数组会令人困惑,不应该创建。它们有时会在索引其他数组时出现。但不要做一个np.zeros((n,0)),除非作为一个实验。


推荐阅读