Append a NumPy array to a NumPy array

匿名 (未验证) 提交于 2019-12-03 02:13:02

问题:

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

And then I want to append it into another NumPy array (just like we create a list of lists). How do we create an array of NumPy arrays 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 "", line 1, in  AttributeError: 'numpy.ndarray' object has no attribute 'append' >>> a array([1, 2, 3])

回答1:

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


回答2:

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.



回答3:

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



回答4:

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.



回答5:

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


回答6:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!