Python 蟒蛇,麻木;如何在数组的开头插入元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20101093/
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
python, numpy; How to insert element at the start of an array
提问by Heiko Herlich
I have an numpy array of complex numbers. So I want to insert zero at start of the array,
and shift the rest of the array one place forward.
我有一个 numpy 复数数组。所以我想在数组的开头插入零,并将数组的其余部分向前移动一个位置。
example:
例子:
a = [1 + 2j, 5 + 7j,..]
I want to make:
我要实现:
a = [0 + 0j, 1 + 2j, 5 + 7j,..]
What's the simplest way to do this?
什么是最简单的方法来做到这一点?
回答by askewchan
Simplest way:
最简单的方法:
a = np.array([1 + 2j, 5 + 7j])
a = np.insert(a, 0, 0)
Then:
然后:
>>> a
array([ 0.+0.j, 1.+2.j, 5.+7.j])
Note that this creates a new array, it does not actually insert the 0into the original array.
请注意,这会创建一个新数组,它实际上并未将 插入0到原始数组中。
There are several alternatives to np.insert, all of which also create a new array:
有几种替代方法np.insert,所有这些方法都会创建一个新数组:
In [377]: a
Out[377]: array([ 1.+2.j, 5.+7.j])
In [378]: np.r_[0, a]
Out[378]: array([ 0.+0.j, 1.+2.j, 5.+7.j])
In [379]: np.append(0, a)
Out[379]: array([ 0.+0.j, 1.+2.j, 5.+7.j])
In [380]: np.concatenate([[0], a])
Out[380]: array([ 0.+0.j, 1.+2.j, 5.+7.j])
In [381]: np.hstack([0, a])
Out[381]: array([ 0.+0.j, 1.+2.j, 5.+7.j])
In [382]: np.insert(a, 0, 0)
Out[382]: array([ 0.+0.j, 1.+2.j, 5.+7.j])
回答by atomh33ls
An alternative is "horizontal stack" (also creates a new array):
另一种选择是“水平堆栈”(也创建一个新数组):
np.hstack((0,a))
回答by tsando
Also, if you have an n-dimensional array, you need to specify the axis as well, otherwise it gets flattened out:
此外,如果您有一个 n 维数组,则还需要指定轴,否则它会变平:
np.insert(my_array, 0, myvalue, axis=1)
回答by kwant
Additionally, if you want to add n numbers of rows with zero values. you can create a zero array and use hstack:
此外,如果您想添加 n 个具有零值的行。您可以创建一个零数组并使用 hstack:
zero_array = np.zeros([n])
new = np.hstack([zero_array,old_array])
回答by W. Zhu
I timed all the five different methods to insert an element at the beginning of an array. Here are the results:
我对所有五种不同的方法进行计时,以便在数组的开头插入一个元素。结果如下:
In [20]: %timeit np.hstack([1, [1, 2, 3]])
10000 loops, best of 3: 30.4 μs per loop
In [21]: %timeit np.insert([1, 2, 3], 0, 1)
10000 loops, best of 3: 46.6 μs per loop
In [22]: %timeit np.r_[[1], [1, 2, 3]]
10000 loops, best of 3: 32.8 μs per loop
In [28]: %timeit np.append(1, [1, 2, 3])
10000 loops, best of 3: 23.4 μs per loop
In [29]: %timeit np.concatenate([[1], [1, 2, 3]])
The slowest run took 6.43 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 8.79 μs per loop

