将numpy数组与lis连接

2024-09-25 08:37:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我想连接numpy数组和list。 像这样:

trainClass = np.ones(len(allDataList[0])).tolist()
trainArray = tfIdfsListTrain.toarray()
np.concatenate( (trainArray, trainClass))

但我不知道该怎么做。在


Tags: numpylennpones数组listconcatenatetolist
1条回答
网友
1楼 · 发布于 2024-09-25 08:37:05

听起来你的列表在变成数组时,没有正确的维数。让我举例说明:

In [323]: arr = np.arange(12).reshape(3,4)
In [324]: alist = list(range(3))
In [325]: np.concatenate((arr,alist))
                                     -
ValueError                                Traceback (most recent call last)
<ipython-input-325-9b72583c40de> in <module>()
  > 1 np.concatenate((arr,alist))

ValueError: all the input arrays must have same number of dimensions
In [326]: arr.shape
Out[326]: (3, 4)

concatenate将任何列表输入转换为数组:

^{pr2}$

arr是2d,因此此数组也需要是2d的:

In [328]: np.array(alist)[:,None].shape
Out[328]: (3, 1)
In [329]: np.concatenate((arr, np.array(alist)[:,None]), axis=1)
Out[329]: 
array([[ 0,  1,  2,  3,  0],
       [ 4,  5,  6,  7,  1],
       [ 8,  9, 10, 11,  2]])

将(3,4)数组与最后一维上的(3,1)数组连接起来很容易。在

我得到的印象是,很多人在没有理解numpy数组的一些基础知识(比如形状和尺寸)的情况下,就开始使用机器学习代码(tensorflowkerassklearn)。在

相关问题 更多 >