追加到numpy数组 [英] Appending to numpy arrays
问题描述
我正在尝试构造一个numpy数组,然后向其附加整数和另一个数组. 我尝试这样做:
I'm trying to construct a numpy array, and then append integers and another array to it. I tried doing this:
xyz_list = frag_str.split()
nums = numpy.array([])
coords = numpy.array([])
for i in range(int(len(xyz_list)/4)):
numpy.append(nums, xyz_list[i*4])
numpy.append(coords, xyz_list[i*4+1:(i+1)*4])
print(atoms)
print(coords)
打印输出仅给出我的空数组.这是为什么?
另外,如何以允许我拥有如下2D数组的方式重写coords
?
Printing out the output only gives my empty arrays. Why is that?
In addition, how can I rewrite coords
in a way that allows me to have 2D arrays like this: array[[0,0,0],[0,0,1],[0,0,-1]]
?
推荐答案
numpy.append
与python的list.append
不同,它不会就地执行操作.因此,您需要将结果分配回一个变量,如下所示.
numpy.append
, unlike python's list.append
, does not perform operations in place. Therefore, you need to assign the result back to a variable, as below.
import numpy
xyz_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
nums = numpy.array([])
coords = numpy.array([])
for i in range(int(len(xyz_list)/4)):
nums = numpy.append(nums, xyz_list[i*4])
coords = numpy.append(coords, xyz_list[i*4+1:(i+1)*4])
print(nums) # [ 1. 5. 9.]
print(coords) # [ 2. 3. 4. 6. 7. 8. 10. 11. 12.]
您可以按以下方式重塑coords
:
You can reshape coords
as follows:
coords = coords.reshape(3, 3)
# array([[ 2., 3., 4.],
# [ 6., 7., 8.],
# [ 10., 11., 12.]])
有关numpy.append
行为的详细信息
More details on numpy.append
behaviour
文档:
返回值:arr的副本,其值附加在axis上.注意 append不会就地发生:分配并填充了一个新数组.
Returns: A copy of arr with values appended to axis. Note that append does not occur in-place: a new array is allocated and filled.
如果您事先知道了numpy
数组输出的形状,则可以有效地通过np.zeros(n)
进行实例化,并在以后用结果填充它.
If you know the shape of your numpy
array output beforehand, it is efficient to instantiate via np.zeros(n)
and fill it with results later.
另一个选择:如果您的计算大量使用了在数组左侧 处插入元素,请考虑使用
Another option: if your calculations make heavy use of inserting elements to the left of an array, consider using collections.deque
from the standard library.
这篇关于追加到numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!