构建一个二维数组,通过将行附加到一个空数组。

huangapple go评论59阅读模式
英文:

Constructing a 2D array by appending rows to an empty array

问题

以下代码段正好满足我的需求,即通过追加列表来填充2D数组,从一个空的列表列表开始。如何仅使用NumPy数组实现相同的效果?

import numpy as np
list = []
list.append([1,2,3])
list.append([4,5,6])
array=np.array(list)
英文:

The following code snippet does exactly what I want, i.e. fill a 2D array by appending lists, starting from an empty list of lists. How do I achieve the same using only numpy arrays?

import numpy as np
list = []
list.append([1,2,3])
list.append([4,5,6])
array=np.array(list)

答案1

得分: 0

这是一个 numpy.append 函数的示例:

import numpy as np
lst = np.ndarray((0, 3)) # 三列的空矩阵
lst = np.append(lst, [[1, 2, 3]], axis=0) # 注意两对方括号
lst = np.append(lst, [[4, 5, 6]], axis=0) # 必须指定轴向

这会得到:

>>> lst
array([[1., 2., 3.],
       [4., 5., 6.]])

无法原地追加值。每次调用 append() 都会分配一个新的数组并复制值。这比追加到列表然后最后转换要慢。

英文:

There is a numpy.append function:

import numpy as np
lst = np.ndarray((0, 3)) # empty matrix with three columns
lst = np.append(lst, [[1, 2, 3]], axis=0) # note the two pairs of brackets
lst = np.append(lst, [[4, 5, 6]], axis=0) # axis is required

This gives:

>>> lst
array([[1., 2., 3.],
       [4., 5., 6.]])

There is no way to append values in-place. Each call to append() will allocate a new array and copy values over. This will be slower than appending to a list and converting at the end.

huangapple
  • 本文由 发表于 2023年5月17日 23:36:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76273831.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定