[英]Insert element into numpy array
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 numpy
array 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 insert
equivalent for numpy
arrays? numpy
数组有insert
等效项吗?
You can use numpy.insert
, though unlike list.insert
it 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])
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
): 基准测试(比
insert
快5倍):
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
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. 要将元素添加到numpy数组,可以使用方法'append'向其传递数组和要添加的元素。 For example:
例如:
import numpy as np dummy = [] dummy = np.append(dummy,12)
this will create an empty array and add the number '12' to it 这将创建一个空数组,并向其中添加数字“ 12”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.