Insert numpy array to an empty numpy array

2.4k views Asked by At

I am trying to create an empty numpy array and then insert newly created arrays into than one. It is important for me not to shape the first numpy array and it has to be empty and then I can be able to add new numpy arrays with different sizes into that one. Something like the following:

A = numpy.array([])
B = numpy.array([1,2,3])
C = numpy.array([5,6])
A.append(B, axis=0)
A.append(C, axis=0)

and I want A to look like this:

[[1,2,3],[5,6]]

When I do the append command I get the following error:

AttributeError: 'numpy.ndarray' object has no attribute 'append'

Any idea how this can be done?

PS: This is not similar to the questions asked before because I am not trying to concatenate two numpy arrays. I am trying to insert a numpy array to another empty numpy array. I know how to do this using lists but it has to be numpy array.

Thanks

3

There are 3 answers

0
B. M. On BEST ANSWER

You can't do that with numpy arrays, because a real 2D numpy is rectangular. For example, np.arange(6).reshape(2,3) return array([[0, 1, 2],[3, 4, 5]]). if you really want to do that, try array([array([1,2,3]),array([5,6])]) which create array([array([1, 2, 3]), array([5, 6])], dtype=object) But you will loose all the numpy power with misaligned data.

4
mbomb007 On

Taken from here. Maybe search for existing questions first.

numpy.append(M, a)
2
rjonnal On

You can do this by converting the arrays to lists:

In [21]: a = list(A)
In [22]: a.append(list(B))
In [24]: a.append(list(C))
In [25]: a
Out[25]: [[1, 2, 3], [5, 6]]

My intuition is that there's a much better solution (either more pythonic or more numpythonic) than this, which might be gleaned from a more complete description of your problem.