【问题标题】:How to insert numpy arrays of size 1 into an empty numpy array?如何将大小为 1 的 numpy 数组插入到空的 numpy 数组中?
【发布时间】:2020-02-23 01:48:20
【问题描述】:

我正在定义两个 NumPy 数组:

PREtrain_labels = np.asarray([inpLblsArray[0:80]])
train_labels = np.array([])
TRstore = 0
i = 0

while i < len(train_images):
  TRstore = np.asarray([PREtrain_labels.item(i)])
  np.append(train_labels, TRstore)
  i = i + 1

在这里,我有一个 NumPy 数组 PREtrain_labels,它包含整数并且是从一个更大的 NumPy 数组中分割出来的。我定义了一个空数组train_labels。我的目标是用数组PREtrain_labels 中选定的整数切片填充空的 NumPy 数组 (train_labels)。但是有一个问题,当我从PREtrain_labels 数组中取出每个整数时,我希望将每个整数放在另一个名为TRstore 的空数组中。然后,我想将TRstore NumPy 数组放入空的train_labels 数组中。但是,当我运行代码并打印最终的 train_labels 数组时,它是空的。

怎么可能解决这个问题?如果np.append() 是错误的使用方法,我应该使用哪一种?上面的代码不会单独运行,因此,我将下面的代码简化为可运行的版本。提前致谢!

loopArr = np.array([1, 2, 3, 4, 5])
a = np.asarray([1, 2, 3, 4, 5])
target = np.array([])
store = 0
i = 0

while i < len(loopArr):
  store = np.asarray([a.item(i)])
  np.append(target, store)
  i = i + 1

print(target)

【问题讨论】:

  • np.append 不是列表追加克隆!不要使用它!
  • 你不能像最初的train_labels那样在数组中放入任何东西。它是形状 (0,) 和浮动 dtype。通过连接一些东西来创建一个新数组是低效的。坚持使用列表追加。

标签: python python-3.x numpy artificial-intelligence


【解决方案1】:
In [30]: res = np.array([])                                                                    
In [31]: np.append(res, np.array(1))                                                           
Out[31]: array([1.])
In [32]: res                                                                                   
Out[32]: array([], dtype=float64)

Out[31} 是一个 1 元素浮点数组 - 因为 res 是浮点数。但请注意,res 没有改变。 np.appendnp.concatenate 的一个构思糟糕的“封面”。

concatenate 对输入的尺寸有点挑剔

In [33]: np.concatenate([ res, np.array(1)])                                                   
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-33-bb45ea1930d0> in <module>
----> 1 np.concatenate([ res, np.array(1)])

<__array_function__ internals> in concatenate(*args, **kwargs)

ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 1 dimension(s) and the array at index 1 has 0 dimension(s)
In [34]: np.concatenate([ res, np.array([1])])                                                 
Out[34]: array([1.])

这将一个 (0,) 形状数组与一个 (1,) 形状连接起来以产生一个 (1,)。 [] 数组几乎没用。

concatenate 获取整个数组列表(甚至列表)。充分利用这一点:

In [35]: np.concatenate([np.array([1]), np.array([2]), [3], [1,2,3]])                          
Out[35]: array([1, 2, 3, 1, 2, 3])

但是你为什么要循环执行append?为什么不列出追加?这可以就地工作,并且相对快速且无错误。为什么要让自己的生活变得艰难?

【讨论】:

  • 我正在尝试将标签输入到需要 numpy 数组作为输入的 CNN 中。我尝试了不起作用的列表。但是,您的解决方案解决了我的问题,谢谢!
猜你喜欢
  • 2015-08-24
  • 2018-07-15
  • 2016-10-09
  • 1970-01-01
  • 2023-01-11
  • 2021-07-14
  • 1970-01-01
  • 2020-10-22
  • 1970-01-01
相关资源
最近更新 更多