英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论