244

I have a numpy_array. Something like [ a b c ].

And then I want to concatenate it with another NumPy array (just like we create a list of lists). How do we create a NumPy array containing NumPy arrays?

I tried to do the following without any luck

>>> M = np.array([])
>>> M
array([], dtype=float64)
>>> M.append(a,axis=0)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
AttributeError: 'numpy.ndarray' object has no attribute 'append'
>>> a
array([1, 2, 3])
Hari
  • 1,561
  • 4
  • 17
  • 26
frazman
  • 32,081
  • 75
  • 184
  • 269
  • 3
    You can create an "array of arrays" (you use an object array), but you almost definitely don't want to. What are you trying to do? Do you just want a 2d array? – Joe Kington Mar 19 '12 at 18:00
  • An array of arrays is called a nested array. Three answers in this thread are about np.append() which does not keep the nested structure. This is because of a question without a clear example. – questionto42 Jul 15 '21 at 22:39

12 Answers12

291
In [1]: import numpy as np

In [2]: a = np.array([[1, 2, 3], [4, 5, 6]])

In [3]: b = np.array([[9, 8, 7], [6, 5, 4]])

In [4]: np.concatenate((a, b))
Out[4]: 
array([[1, 2, 3],
       [4, 5, 6],
       [9, 8, 7],
       [6, 5, 4]])

or this:

In [1]: a = np.array([1, 2, 3])

In [2]: b = np.array([4, 5, 6])

In [3]: np.vstack((a, b))
Out[3]: 
array([[1, 2, 3],
       [4, 5, 6]])
endolith
  • 25,479
  • 34
  • 128
  • 192
  • 1
    Hi when i run this i get this np.concatenate((a,b),axis=1) Output: array([1, 2, 3, 2, 3, 4]) But what I looking for is numpy 2d array?? – frazman Mar 19 '12 at 18:05
  • 3
    @Fraz: I've added Sven's `vstack()` idea. You know you can create the array with `array([[1,2,3],[2,3,4]])`, right? – endolith Mar 19 '12 at 18:14
  • concatenate() is the one I needed. – kakyo Feb 19 '15 at 00:17
  • 1
    [`numpy.vstack`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html) can accept more than 2 arrays in the sequence argument. Thus if you need to combine more than 2 arrays, vstack is more handy. – ruhong Oct 22 '15 at 12:57
  • 1
    @oneleggedmule `concatenate` can also take multiple arrays – endolith Oct 22 '15 at 13:28
  • When i try to concatenate i get a single dimension array instead of 2. –  Aug 06 '20 at 10:19
  • @user12067965 are you sure you're using the double parens... ie `concatenate((` vs`concatenate(` – Rhubarb May 21 '21 at 18:46
94

Well, the error message says it all: NumPy arrays do not have an append() method. There's a free function numpy.append() however:

numpy.append(M, a)

This will create a new array instead of mutating M in place. Note that using numpy.append() involves copying both arrays. You will get better performing code if you use fixed-sized NumPy arrays.

Uli Köhler
  • 13,012
  • 16
  • 70
  • 120
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • Hi.. when i try this.. I get this >>> np.append(M,a) array([ 1., 2., 3.]) >>> np.append(M,b) array([ 2., 3., 4.]) >>> M array([], dtype=float64) I was hoping M to be a 2D array?? – frazman Mar 19 '12 at 18:06
  • 9
    @Fraz: Have a look at `numpy.vstack()`. – Sven Marnach Mar 19 '12 at 18:08
  • I think this should be the accepted answer as it precisely answers to the point. – Prasad Raghavendra Mar 27 '20 at 19:15
  • 2
    This answer does not fit to the question. It just makes a flattened array out of any structure you put in. For example for `np.append(arr1,arr2)` with arr1 and arr2 being 3x3 arrays, the output structure is 1x18: `array([1, 2, 0, 0, 1, 1, 1, 1, 2, 0, 1, 0, 0, 0, 1, 1, 0, 1])`. Which is not what was asked for, instead, a nested array was asked for. – questionto42 Jul 15 '21 at 22:30
40

You may use numpy.append()...

import numpy

B = numpy.array([3])
A = numpy.array([1, 2, 2])
B = numpy.append( B , A )

print B

> [3 1 2 2]

This will not create two separate arrays but will append two arrays into a single dimensional array.

buydadip
  • 8,890
  • 22
  • 79
  • 154
Zhai Zhiwei
  • 441
  • 4
  • 3
10

I found this link while looking for something slightly different, how to start appending array objects to an empty numpy array, but tried all the solutions on this page to no avail.

Then I found this question and answer: How to add a new row to an empty numpy array

The gist here:

The way to "start" the array that you want is:

arr = np.empty((0,3), int)

Then you can use concatenate to add rows like so:

arr = np.concatenate( ( arr, [[x, y, z]] ) , axis=0)

See also https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html

Community
  • 1
  • 1
Clay Coleman
  • 331
  • 3
  • 7
10

Sven said it all, just be very cautious because of automatic type adjustments when append is called.

In [2]: import numpy as np

In [3]: a = np.array([1,2,3])

In [4]: b = np.array([1.,2.,3.])

In [5]: c = np.array(['a','b','c'])

In [6]: np.append(a,b)
Out[6]: array([ 1.,  2.,  3.,  1.,  2.,  3.])

In [7]: a.dtype
Out[7]: dtype('int64')

In [8]: np.append(a,c)
Out[8]: 
array(['1', '2', '3', 'a', 'b', 'c'], 
      dtype='|S1')

As you see based on the contents the dtype went from int64 to float32, and then to S1

lukecampbell
  • 14,728
  • 4
  • 34
  • 32
8

Actually one can always create an ordinary list of numpy arrays and convert it later.

In [1]: import numpy as np

In [2]: a = np.array([[1,2],[3,4]])

In [3]: b = np.array([[1,2],[3,4]])

In [4]: l = [a]

In [5]: l.append(b)

In [6]: l = np.array(l)

In [7]: l.shape
Out[7]: (2, 2, 2)

In [8]: l
Out[8]: 
array([[[1, 2],
        [3, 4]],

       [[1, 2],
        [3, 4]]])
Michael Ma
  • 872
  • 8
  • 20
2

I had the same issue, and I couldn't comment on @Sven Marnach answer (not enough rep, gosh I remember when Stackoverflow first started...) anyway.

Adding a list of random numbers to a 10 X 10 matrix.

myNpArray = np.zeros([1, 10])
for x in range(1,11,1):
    randomList = [list(np.random.randint(99, size=10))]
    myNpArray = np.vstack((myNpArray, randomList))
myNpArray = myNpArray[1:]

Using np.zeros() an array is created with 1 x 10 zeros.

array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])

Then a list of 10 random numbers is created using np.random and assigned to randomList. The loop stacks it 10 high. We just have to remember to remove the first empty entry.

myNpArray

array([[31., 10., 19., 78., 95., 58.,  3., 47., 30., 56.],
       [51., 97.,  5., 80., 28., 76., 92., 50., 22., 93.],
       [64., 79.,  7., 12., 68., 13., 59., 96., 32., 34.],
       [44., 22., 46., 56., 73., 42., 62.,  4., 62., 83.],
       [91., 28., 54., 69., 60., 95.,  5., 13., 60., 88.],
       [71., 90., 76., 53., 13., 53., 31.,  3., 96., 57.],
       [33., 87., 81.,  7., 53., 46.,  5.,  8., 20., 71.],
       [46., 71., 14., 66., 68., 65., 68., 32.,  9., 30.],
       [ 1., 35., 96., 92., 72., 52., 88., 86., 94., 88.],
       [13., 36., 43., 45., 90., 17., 38.,  1., 41., 33.]])

So in a function:

def array_matrix(random_range, array_size):
    myNpArray = np.zeros([1, array_size])
    for x in range(1, array_size + 1, 1):
        randomList = [list(np.random.randint(random_range, size=array_size))]
        myNpArray = np.vstack((myNpArray, randomList))
    return myNpArray[1:]

a 7 x 7 array using random numbers 0 - 1000

array_matrix(1000, 7)

array([[621., 377., 931., 180., 964., 885., 723.],
       [298., 382., 148., 952., 430., 333., 956.],
       [398., 596., 732., 422., 656., 348., 470.],
       [735., 251., 314., 182., 966., 261., 523.],
       [373., 616., 389.,  90., 884., 957., 826.],
       [587., 963.,  66., 154., 111., 529., 945.],
       [950., 413., 539., 860., 634., 195., 915.]])
Coffee and Code
  • 885
  • 14
  • 16
2

Try this code :

import numpy as np

a1 = np.array([])

n = int(input(""))

for i in range(0,n):
    a = int(input(""))
    a1 = np.append(a, a1)
    a = 0

print(a1)

Also you can use array instead of "a"

Mehdi
  • 21
  • 4
1

If I understand your question, here's one way. Say you have:

a = [4.1, 6.21, 1.0]

so here's some code...

def array_in_array(scalarlist):
    return [(x,) for x in scalarlist]

Which leads to:

In [72]: a = [4.1, 6.21, 1.0]

In [73]: a
Out[73]: [4.1, 6.21, 1.0]

In [74]: def array_in_array(scalarlist):
   ....:     return [(x,) for x in scalarlist]
   ....: 

In [75]: b = array_in_array(a)

In [76]: b
Out[76]: [(4.1,), (6.21,), (1.0,)]
linhares
  • 504
  • 6
  • 17
1

This is for people working with numpy's ndarrays. The function numpy.concatenate() does work as well.

>>a = np.random.randint(0,9, size=(10,1,5,4))
>>a.shape
(10, 1, 5, 4)

>>b = np.random.randint(0,9, size=(15,1,5,4))
>>b.shape
(15, 1, 5, 4)

>>X = np.concatenate((a, b))
>>X.shape
(25, 1, 5, 4)

Much the same way as vstack()

>>Y = np.vstack((a,b))
>>Y.shape
(25, 1, 5, 4)
arilwan
  • 3,374
  • 5
  • 26
  • 62
0

As you want to concatenate along an existing axis (row wise), np.vstack or np.concatenate will work for you.

For a detailed list of concatenation operations, refer to the official docs.

DevLoverUmar
  • 11,809
  • 11
  • 68
  • 98
0

There is a handfull of method to stack arrays together, depending on the direction of the stack. You may consider np.stack() (doc), np.vstack() (doc) and np.hstack() (doc) for example.

jeandemeusy
  • 226
  • 3
  • 12