Python 将元素插入 numpy 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21761256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert element into numpy array
提问by Gabriel
Lists have a very simple method to insert elements:
列表有一个非常简单的方法来插入元素:
a = [1,2,3,4]
a.insert(2,66)
print a
[1, 2, 66, 3, 4]
For a numpyarray I could do:
对于numpy数组,我可以这样做:
a = np.asarray([1,2,3,4])
a_l = a.tolist()
a_l.insert(2,66)
a = np.asarray(a_l)
print a
[1 2 66 3 4]
but this is very convoluted.
但这很复杂。
Is there an insertequivalent for numpyarrays?
数组是否有insert等价物numpy?
采纳答案by Ashwini Chaudhary
You can use numpy.insert, though unlike list.insertit returns a new array because arrays in NumPy have fixed size.
您可以使用numpy.insert,但与list.insert它不同的是,它返回一个新数组,因为 NumPy 中的数组具有固定大小。
>>> import numpy as np
>>> a = np.asarray([1,2,3,4])
>>> np.insert(a, 2, 66)
array([ 1, 2, 66, 3, 4])
回答by Kasramvd
If you just want to insert items in consequent indices, as a more optimized way you can use np.concatenate()to concatenate slices of the array with your intended items:
如果您只想在后续索引中插入项目,作为一种更优化的方式,您可以使用np.concatenate()将数组的切片与您想要的项目连接起来:
For example in this case you can do:
例如,在这种情况下,您可以执行以下操作:
In [21]: np.concatenate((a[:2], [66], a[2:]))
Out[21]: array([ 1, 2, 66, 3, 4])
Benchmark (5 time faster than insert):
基准测试(比 快 5 倍insert):
In [19]: %timeit np.concatenate((a[:2], [66], a[2:]))
1000000 loops, best of 3: 1.43 us per loop
In [20]: %timeit np.insert(a, 2, 66)
100000 loops, best of 3: 6.86 us per loop
And here is a benchmark with larger arrays (still 5 time faster):
这是具有更大阵列的基准测试(仍然快 5 倍):
In [22]: a = np.arange(1000)
In [23]: %timeit np.concatenate((a[:300], [66], a[300:]))
1000000 loops, best of 3: 1.73 us per loop
In [24]: %timeit np.insert(a, 300, 66)
100000 loops, best of 3: 7.72 us per loop
回答by kiran
To add elements to a numpy array you can use the method 'append' passing it the array and the element that you want to add. For example:
要将元素添加到 numpy 数组,您可以使用 'append' 方法将数组和要添加的元素传递给它。例如:
import numpy as np
dummy = []
dummy = np.append(dummy,12)
import numpy as np
dummy = []
dummy = np.append(dummy,12)
this will create an empty array and add the number '12' to it
这将创建一个空数组并向其添加数字“12”

