Mahsa
Mahsa

Reputation: 271

Concatenate numpy array with list

I want to concatenate numpy array with list. like this:

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

but I don't know how do I do it.

Upvotes: 0

Views: 2880

Answers (1)

hpaulj
hpaulj

Reputation: 231355

Sounds like your list, when turned into an array, doesn't have the right number of dimensions. Let me illustrate:

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 turns any list inputs into arrays:

In [327]: np.array(alist).shape
Out[327]: (3,)

arr is 2d, so this array needs to be 2d as well:

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]])

It is easy to concatenate a (3,4) array with a (3,1) array on the last dimension.

I get the impression that a lot of people are jumping into machine learning code (tensorflow, keras, sklearn) without understanding some of the basics of numpy arrays, such as shape and dimensions.

Upvotes: 2

Related Questions