user - 2 months ago 7

Python Question

How do you store an entire array into another array

suppose I have an array

`data = np.array([], dtype=float, ndmin=2)`

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

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

How do you store the values such that

`data = [ [1,2,3],`

[4,5,6] ]

My current method is

`data= np.append(data, a)`

data= np.append(data, b)

However this results in [ 1,2,3,4,6]

Answer

You mean like:

```
>>> data = np.array([a,b])
>>> data
array([[1, 2, 3],
[4, 5, 6]])
```

If you want to do it stepwise, you *can* use append, but you need to make sure all your arguments are rank 2 (or wrapped in a list). Right now, `a`

and `b`

are both rank 1 so if you try to append along a particular axis, you'll get an error. I.e. what you need to do is:

```
>>> data = np.empty([0,3]); data
array([], shape=(0, 3), dtype=float64)
>>> data = np.append(data, np.array([a]), axis=0); data
array([[ 1., 2., 3.]])
>>> data = np.append(data, np.array([b]), axis=0); data
array([[ 1., 2., 3.],
[ 4., 5., 6.]])
```

PS. However, if the number of rows in

`data`

are known (say, 100), you're probably better off preallocating, i.e. initializing it as `np.empty([100,3])`

and filling by index, (e.g. `data[0,:] = a`

)
Source (Stackoverflow)

Comments