如何将大小为1的numpy数组插入到一个空的numpy数组中?

我定义了两个NumPy数组:

PREtrain_labels = np.asarray([inpLblsArray[0:80]])train_labels = np.array([])TRstore = 0i = 0while 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的空数组中。然后,我希望将TRstoreNumPy数组放入空的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 = 0i = 0while i < len(loopArr):  store = np.asarray([a.item(i)])  np.append(target, store)  i = i + 1print(target)

回答:

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}是一个包含一个元素的浮点数组 – 因为res是浮点型。但请注意,res没有改变。np.append只是对np.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?为什么不使用列表追加?列表追加是原地操作,相对快速且无错误。为什么要让自己生活变得艰难?

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注