问题:将NumPy数组追加到NumPy数组

我有一个numpy_array。有点像[ a b c ]

然后,我想将其附加到另一个NumPy数组中(就像我们创建列表列表一样)。我们如何创建包含NumPy数组的NumPy数组的数组?

我尝试做以下没有运气的事情

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

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

回答 0

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

或这个:

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

回答 1

好吧,错误消息说明了一切:NumPy数组没有append()方法。numpy.append()但是有一个免费功能:

numpy.append(M, a)

这将创建一个新数组,而不是M在原处进行变异。请注意,使用numpy.append()涉及复制两个阵列。如果使用固定大小的NumPy数组,您将获得性能更好的代码。

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.


回答 2

您可以使用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]

这不会创建两个单独的数组,但是会将两个数组追加到一个维数组中。

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.


回答 3

Sven说了这一切,只是非常谨慎,因为在调用append时会自动进行类型调整。

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

如您所见,dtype从int64到float32,然后到S1

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

我在寻找稍微不同的东西时找到了此链接,如何开始将数组对象附加到空的 numpy数组,但是尝试了此页上的所有解决方案,但无济于事。

然后我找到了这个问题和答案:如何向空的numpy数组添加新行

要点:

“启动”所需阵列的方法是:

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

然后,您可以使用串联添加行,如下所示:

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

另请参阅https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html

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


回答 5

实际上,总可以创建一个普通的numpy数组列表,并在以后进行转换。

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

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

我遇到了同样的问题,无论如何我都无法评论@Sven Marnach的答案(没有足够的代表,我记得Stackoverflow首次启动时就…)。

将随机数列表添加到10 X 10矩阵中。

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

使用np.zeros()可以创建一个具有1 x 10个零的数组。

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

然后,使用np.random创建10个随机数的列表,并将其分配给randomList。循环将其堆叠为10高。我们只需要记住删除第一个空条目。

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

所以在一个函数中:

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

使用随机数0-1000的7 x 7数组

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

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

回答 7

如果我理解您的问题,这是一种方法。说您有:

a = [4.1, 6.21, 1.0]

所以这是一些代码…

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

这导致:

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

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

回答 8

试试这个代码:

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)

您也可以使用数组代替“ a”

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”


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。