python - 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 新手,所以我的知识非常基础。
解决方案
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 = 0
c
如果我尝试将值分配给 的列,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,:].shape
is (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))
,除非作为一个实验。
推荐阅读
- python - XPath 总是返回一个空列表
- python - 无法通过代理链运行 selenium python 脚本
- sql - 基于同一视图中的列添加其他列并放置值
- android-studio - 是否没有退出接口库的 v7.28:0:0?
- python - 如何从 Pytest 中的另一个测试开始测试?
- typescript - 从 Flow 迁移到 Typescript:TS 中的 $Keys 等价物?
- c# - 收到错误“使用未分配的局部变量”
- .net-core - Azure DevOps 管道“dotnet build”找不到项目
- mysql - Perl DBD::MySQL 执行不支持 limit 关键字后的字符串参数。始终视为数字
- bootstrap-4 - 引导行跨度并自下而上对齐控件